//#define DISABLE_ARGLIST

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Meta;

namespace Meta.Editor {
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Editor : System.Windows.Forms.Form {
		public static CodeBox.Style defaultNormalStyle = new CodeBox.Style(new Font("Arial", 11.0F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,	((System.Byte)(0))), Color.Black);
		public static CodeBox.Style defaultTitleStyle = new CodeBox.Style(new Font("Arial", 13.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point,	((System.Byte)(0))), Color.Black);
		public static CodeBox.Style defaultCommentStyle = new CodeBox.Style(new Font("Arial", 11.0F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point,	((System.Byte)(0))), Color.Black);
		public static readonly System.Drawing.Icon DefaultIcon = ((System.Drawing.Icon)(new System.Resources.ResourceManager(typeof(Editor)).GetObject("$this.Icon")));
		public static Color defaultBackgroundColor = Color.LightGray;
		//public static bool indentDefsLispStyle = false;
		public static bool fastMode=false;
		public static bool insertMatchingBrackets=false;
		public static bool BlankLinesMarkTopLevelRegions = false;
		public static bool OnlyTopLevelDefs = false;

		private System.Windows.Forms.Timer arglistTimer;
		public static int arglistPeriod = 3000;
		private string arglistOperator;
		public FileToken fileToken;
		// Need to maintain our own modified flag  because code.Modified gets set for
		// events that don't actually change the file text.
		bool reallyModified = false;

		private System.Windows.Forms.MenuItem formatBullet;
		private System.Windows.Forms.MenuItem speedUpEditorMenuItem;
		private System.Windows.Forms.MenuItem InterruptExecution;
		private System.Windows.Forms.MenuItem fontMenuItem;
		private System.Windows.Forms.MenuItem examplesMenuItem;
		private System.Windows.Forms.MenuItem advancedMenu;
		private System.Windows.Forms.MenuItem backgroundColorMenuItem;
		private static ColorDialog colorDialog = new ColorDialog();
		private System.Windows.Forms.MenuItem forceGCMenuItem;
		private System.Windows.Forms.MenuItem editorSubmenu;
		private System.Windows.Forms.MenuItem debugSubmenu;
		private System.Windows.Forms.MenuItem wizardSubmenu;
		private System.Windows.Forms.MenuItem loadMenuItem;
		private System.Windows.Forms.MenuItem pasteCommandMenuItem;
		private System.Windows.Forms.MenuItem pasteNextCommandMenuItem;
		private System.Windows.Forms.MenuItem undoMenuItem;
		private System.Windows.Forms.MenuItem NormalStyleMenuItem;
		private System.Windows.Forms.MenuItem TitleStyleMenuItem;
		private System.Windows.Forms.MenuItem CommentStyleMenuItem;
		private System.Windows.Forms.MenuItem styleMenu;
		private System.Windows.Forms.MenuItem editStylesMenuItem;
		private System.Windows.Forms.MenuItem setDefaultMenuItem;
		private System.Windows.Forms.MenuItem executeSelectionMenuItem;
		private System.Windows.Forms.MenuItem searchMenuItem;
		private System.Windows.Forms.MenuItem fileSeparator1;
		private System.Windows.Forms.MenuItem fileSeparator2;
		private System.Windows.Forms.MenuItem fileSeparator3;
		private System.Windows.Forms.MenuItem editSeparator1;
		private System.Windows.Forms.MenuItem editSeparator2;
		private System.Windows.Forms.MenuItem editSeparator3;
		private System.Windows.Forms.MenuItem editSeparator4;
		private System.Windows.Forms.MenuItem formatSeparator1;
		private System.Windows.Forms.MenuItem formatSeparator2;
		private System.Windows.Forms.MenuItem formatSeparator3;
		private System.Windows.Forms.MenuItem formatSeparator4;
		private System.Windows.Forms.MenuItem styleSeparator1;
		private System.Windows.Forms.MenuItem executeSeparator1;
		private System.Windows.Forms.MenuItem executeSeparator2;
		private System.Windows.Forms.MenuItem helpSeparator1;
		private System.Windows.Forms.MenuItem contextCut;
		private System.Windows.Forms.MenuItem contextCopy;
		private System.Windows.Forms.MenuItem contextPaste;
		private System.Windows.Forms.MenuItem contextSeparator1;
		private System.Windows.Forms.MenuItem contextExecute;
		private System.Windows.Forms.MenuItem contextSingleStep;
		private System.Windows.Forms.MenuItem contextInspect;
		private System.Windows.Forms.MenuItem contextSeparator2;
		private System.Windows.Forms.MenuItem contextFindDefinition;
		private System.Windows.Forms.MenuItem contextBreakpoint;
		private System.Windows.Forms.MenuItem contextSeparator3;
		private System.Windows.Forms.MenuItem findMenuItem;
		private System.Windows.Forms.MenuItem tailRecursionMenu;
		private System.Windows.Forms.MenuItem fullTailRecursionMenuItem;
		private System.Windows.Forms.MenuItem selfTailRecursionMenuItem;
		private System.Windows.Forms.MenuItem noTailRecursionMenuItem;
		private System.Windows.Forms.MenuItem reindentMenuItem;
		private System.Windows.Forms.MenuItem reindentAllMenuItem;
		private System.Windows.Forms.MenuItem menuItem2;
		private System.Windows.Forms.MenuItem restyleMenuItem;
		private System.Windows.Forms.MenuItem restyleAllMenuItem;
		private System.Windows.Forms.MenuItem restyleAllPreservingCommentsMenuItem;
		private System.Windows.Forms.MenuItem clearAllBreakpointsMenuItem;
		private System.Windows.Forms.MenuItem breakpointExpressionMenuItem;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem continueExecutionMenuItem;
		private System.Windows.Forms.MenuItem beginnerModeMenuItem;
		private System.Windows.Forms.MenuItem contextBreakpointExpressionMenuItem;
		private System.Windows.Forms.MenuItem contextContinueExecutionMenuItem;
		private System.Windows.Forms.MenuItem windowsMenu;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem traceMenuItem;
		private System.Windows.Forms.MenuItem clearAllTracesMenuItem;
		private System.Windows.Forms.MenuItem contextTrace;
		private System.Windows.Forms.MenuItem menuItem4;
		private System.Windows.Forms.MenuItem traceLoadMenuItem;
		private System.Windows.Forms.MenuItem zoomMenu;
		private System.Windows.Forms.MenuItem zoom120;
		private System.Windows.Forms.MenuItem zoom110;
		private System.Windows.Forms.MenuItem zoom100;
		private System.Windows.Forms.MenuItem zoom90;
		private System.Windows.Forms.MenuItem zoom80;
		private System.Windows.Forms.MenuItem zoom150;
		private System.Windows.Forms.MenuItem zoom200;
		private System.Windows.Forms.MenuItem zoom300;
		private System.Windows.Forms.MenuItem ShowReferencesMenuItem;
		private System.Windows.Forms.MenuItem ShowReferencesMenuItem2;
		private System.Windows.Forms.MenuItem ISearchMenuItem;
		private System.Windows.Forms.MenuItem fKeyMenuItem;
		private System.Windows.Forms.MenuItem findUnbalancedMenuItem;
		private System.Windows.Forms.MenuItem menuItem5;
		private System.Windows.Forms.MenuItem ReplaceMenuItem;
		private System.Windows.Forms.MenuItem RemoveWhitespaceMenuItem;
		private System.Windows.Forms.MenuItem CheckMenu;
		private System.Windows.Forms.MenuItem CheckMenuItem;
		private System.Windows.Forms.MenuItem AutoCheckMenuItem;
		private System.Windows.Forms.MenuItem menuItem6;
		protected System.Windows.Forms.MenuItem GotoMenuItem;
		private System.Windows.Forms.MenuItem RecenterMenuItem;
		private System.Windows.Forms.ContextMenu contextMenu;
		private System.Windows.Forms.MenuItem traceAnalysisMenuItem;
		private System.Windows.Forms.MenuItem menuItem7;
		private System.Windows.Forms.MenuItem contextFindUsesMenuItem;

		///
		/// Stuff for keeping track of the set of editor windows
		///
		private static Hashtable editorTable = new Hashtable();
		public static Editor FindEditor(FileToken fullPathName) {
			return FindEditor(fullPathName, true);
		}
		public static Editor FindEditor(FileToken fullPathName, bool create) {
			object probe = editorTable[fullPathName];

			if (probe is Editor)
				return (Editor)probe;
			else if (create && fullPathName.Path!=null) {
				Editor e = new Editor(fullPathName);
				e.Show();

				return e;
			} else
				return null;
		}

		///
		/// Namespace<->buffer tracking
		///
		static Hashtable fileNamespaceTable = new Hashtable();
		// Called when the user does [namespace <foo>]
		static void NotePackage() {
			FileToken file = Meta.TopLevel.CurrentSourceFileToken;

			if (file==null)
				return;

			// Remember the new namespace for this file.
			fileNamespaceTable[file] = Namespace.CurrentNamespace;
			Editor e = FindEditor(file, false);
			if (e!=null)
				e.ShowNamespace();

			// Kluge - we want a namespace command executed in the main listener to change the global default namespace
			if (e == Listener.mainListener)
				Meta.Namespace.currentNamespaceFluid.DefaultValue = Namespace.CurrentNamespace;
		}
		public static Namespace FileNamespace(FileToken token) {
			object probe = fileNamespaceTable[token];;
			if (probe!=null)
				return (Namespace)probe;
			else
				return PackageDirectory.Find(token.Path);
		}

		private void RemoveFromEditorTable() {
			lock (editorTable) {
				editorTable[fileToken] = null;
			}
		}
		private void AddToEditorTable() {
			lock (editorTable) {
				editorTable[fileToken] = this;
			}
		}

		public static void SetAllCursorsInternal(Cursor newCursor) {
			lock (editorTable) {
				foreach (DictionaryEntry window in editorTable) {
					Editor w = window.Value as Editor;

					if (w != null) 
						w.code.Cursor = newCursor;
				}
			}
		}

		public static bool CloseAllEditorWindows() {
			ArrayList allWindows = new ArrayList();
			// This is subtle;  We can't close the windows
			// inside the enumeration of the editorTable
			// because closing mutates the editorTable.
			lock (editorTable) {
				foreach (DictionaryEntry window in editorTable) {
					Editor w = window.Value as Editor;

					if (w != null && !(w is Listener)) 
						allWindows.Add(w);
				}
			}
			foreach (Editor e in allWindows) {
				e.Close();
				if (e.Controls.Count>0)
					return true;
			}
			return false;
		}

		protected static void DumpEditors(IDictionary dump) {
			ArrayList allWindows = new ArrayList();
			lock (editorTable) {
				foreach (DictionaryEntry window in editorTable) {
					Editor w = window.Value as Editor;

					if (w != null && w.code.Rtf.Length<50000) 
						allWindows.Add(new EditorState(w.Name, w.code.Rtf));
				}
			}
			dump.Add("Editor windows", allWindows);
		}

		[Serializable]
		protected class EditorState : IObjectReference {
			string name;
			string contents;

			public EditorState(string name, string contents) {
				this.name = name;
				this.contents = contents;
			}

			object IObjectReference.GetRealObject(StreamingContext ignore) {
				Editor ed = new Editor("Dump of "+((name==null)?"unnamed":name), contents);
				ed.Show();
				return ed;
			}
		}

		private System.Windows.Forms.MenuItem formatBold;
		private System.Windows.Forms.MenuItem formatItalic;
		private System.Windows.Forms.MenuItem formatSuperscript;
		private System.Windows.Forms.MenuItem formatSubscript;
		private System.Windows.Forms.MenuItem formatGrow;
		private System.Windows.Forms.MenuItem formatShrink;
		private System.Windows.Forms.MenuItem formatMenu;
		private System.Windows.Forms.MenuItem lowLevelDebugMenuItem;
		private System.Windows.Forms.MenuItem showDetailMenuItem;
	
		delegate void StupidDelegateDecl(Cursor x);
		private static StupidDelegateDecl setCursorDelegate = new StupidDelegateDecl(SetAllCursorsInternal);

		public void SetAllCursors(Cursor newCursor) {
			Invoke(setCursorDelegate, new object[1] {newCursor});
		}

		static Expression TopLevelExpression(Expression e) {
			if (e.enclosingExpression==null)
				return e;
			else
				return TopLevelExpression(e.enclosingExpression);
		}

		static int SourceOffset(Expression e) {
			if (e.sourceLocation<0)
				return 0;
			Expression top = TopLevelExpression(e);
			if (top.sourceLocation<0)
				return 0;
			else
				return e.sourceLocation-top.sourceLocation;
		}

		delegate void StupidDelegateType(Meta.Expression e, bool loc, bool raise);

		// This is the version to be called from Meta code
		public static void EditSource(Meta.Expression e) {
			Listener.mainListener.Invoke(new StupidDelegateType(EditSource), new object[] { e, true, true });
		}

		// Should not be called from Meta code
		protected static void EditSource(Meta.Expression e, bool localizeToExpression, bool raise) {
			if (e==null)
				return;

			if (e.sourceFile!=null) {
				Editor p = FindEditor(e.sourceFile);
				if (p!=null) {
					p.code.LockWindow();
					// e.definedIn gets set to null for a globalvariablereference that's the operator in an application, at least in a method
					// find out why.
					if (e.definedIn==null && e.enclosingExpression!=null && e.enclosingExpression.definedIn!=null)
						e = e.enclosingExpression;
					if (e.definedIn==null) {
						if (e.sourceLocation>=0) {
							p.code.userSelection = new Region(e.sourceLocation, 0);
							p.code.RestoreUserSelection();
							p.code.HideSelection = false;
							if (raise)
								p.BringToFront();
							p.code.ScrollToCaret();
							System.Windows.Forms.Application.DoEvents();  // Force it to scroll to the beginning before highlighting.
							p.code.MaybeHighlightAfter();
						} 
#if INFORMNOSOURCEFILE
						else
							MessageBox.Show("Sorry, I can't find the location of that expression in the source file.", "Can't find source code", MessageBoxButtons.OK);
#endif
					} else {
						// Yuk!
						string headerPattern = Regex.Escape(e.definedIn);
						if (e.definedIn.StartsWith("["))
							// It's a method description; hack it to be tolerant of extra whitespace
							headerPattern = headerPattern.Replace("\\ ","\\s+");
						else
							// It's a variable name; hack it to prevent it from matching the interiors of words
							//headerPattern = headerPattern+"[ $\r\n)\\]]";
							headerPattern = headerPattern+"[\\s\\]]";
						String searchPattern = "[[(]define[^[( ]* +[[(]*"+headerPattern;
						System.Text.RegularExpressions.Regex r = new Regex(searchPattern);
						string text = p.code.Text;
						Match m = r.Match(text);
						//int start = text.IndexOf("[define "+e.definedIn);
						//if (start>=0) {
						if (m.Success) {
							int start = m.Index;
							p.code.ScrollToPosition(start);
							if (localizeToExpression) {
								p.code.userSelection.start += SourceOffset(e);
								p.code.RestoreUserSelection();
								System.Windows.Forms.Application.DoEvents();  // Force it to scroll to the beginning before highlighting
								p.code.MaybeHighlightAfter();
							} else {
								int offset = SourceOffset(e);
								p.code.userSelection = new Region((offset>0)?offset:start, 0);
								p.code.RestoreUserSelection();
							}
							p.code.HideSelection = false;
							p.code.ScrollToCaret();
							if (raise)
								p.BringToFront();
						} else
							MessageBox.Show("Sorry, I can't find the location of that expression in the source file.  I'm using the last known location of the expression.", "Can't find source code", MessageBoxButtons.OK);
					}
					p.SnapToDebugger();
					p.code.ScrollToTop();
					p.code.UnlockWindowDammit();
				}
			} else
				MessageBox.Show("Sorry, I can't determine what file the code came from.", "Can't find source code", MessageBoxButtons.OK);
			SetAllCursorsInternal(Cursors.Default);
		}

		public void SnapToDebugger() {
			int screenEnd = Screen.PrimaryScreen.Bounds.Right;
			Inspector d = Meta.TopLevel.CurrentDebugger;
			if (d!=null  && !d.IsDisposed && d.Visible) {  // paranoid
				d.Top = this.Top;

				int w = d.Width;
				if (Left>(w+1))
					d.Left = this.Left-(w+1);
				else if ((this.Right+w+1) < screenEnd)
					d.Left = this.Right+1;
				// else can't do anything because the debugger won't fit
					
				d.BringToFront();
				//this.BringToFront();
			}
		}

		public string saveFileName = null;
		private StringReader myReader;
	
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
		private System.Windows.Forms.MenuItem File;
		private System.Windows.Forms.MenuItem Execute;
		private System.Windows.Forms.MenuItem Edit;
		private System.Windows.Forms.MenuItem Cut;
		private System.Windows.Forms.MenuItem Copy;
		private System.Windows.Forms.MenuItem Paste;
		private System.Windows.Forms.MenuItem Evaluate;
		private System.Windows.Forms.MenuItem StopExec;
		private System.Windows.Forms.MenuItem FileNew;
		private System.Windows.Forms.MenuItem FileOpen;
		private System.Windows.Forms.MenuItem FileClose;
		private System.Windows.Forms.MenuItem FileSave;
		private System.Windows.Forms.MenuItem FileSaveAs;
		private System.Windows.Forms.MenuItem FileExit;
		private System.Windows.Forms.MenuItem HelpMenu;
		private System.Windows.Forms.MenuItem FilePrint;
		private System.Windows.Forms.MenuItem PreviewMenu;
		private System.Windows.Forms.MenuItem PrinterSettingsMenu;
		private System.Windows.Forms.PrintDialog printDialog1;
		private System.Drawing.Printing.PrintDocument ThePrintDocument;
		private System.Windows.Forms.StatusBar statusBar;
		private System.Windows.Forms.MainMenu mainMenu;
		private System.Windows.Forms.MenuItem SingleStepMenuItem;
		private System.Windows.Forms.MenuItem inspectMenuItem;
		private System.Windows.Forms.StatusBarPanel valuePanel;
		private System.Windows.Forms.StatusBarPanel arglistPanel;
		private System.Windows.Forms.MenuItem executeAllMenuItem;
		private System.Windows.Forms.MenuItem SelectAll;
		private System.Windows.Forms.MenuItem FindDefinitionMenuItem;
		private System.Windows.Forms.MenuItem transposeMenuItem;
		protected CodeBox code;
		private System.Windows.Forms.MenuItem breakpointMenuItem;

		private void EditorInit() {
			if (!DesignMode) {
				this.ThePrintDocument = new System.Drawing.Printing.PrintDocument();
#if SYNTAXHIGHLIGHTING
				HighLightMenu.Checked = EditorConfiguration.doHighlight;
#endif
				Controls.Add(code);
				code.ContextMenu = contextMenu;
				arglistTimer = new System.Windows.Forms.Timer();
				arglistTimer.Stop();
				arglistTimer.Tick += new EventHandler(ShowDocumentation);
				arglistTimer.Interval = arglistPeriod;
				SetArglistText("");
				code.MarkUndo();
				//code.SpacePressed += new Thunk(MaybeShowArglist);
#if !DISABLE_ARGLIST
				code.SelectionChanged += new EventHandler(MaybeShowArglist);
#endif
				code.VerticalPositionChanged += new Thunk(UpdateVariableValue);
				//code.ModifiedChanged += new EventHandler(HandleModified);
				code.TextChanged += new EventHandler(HandleModified);
				Closing += new CancelEventHandler(HandleClose);
				System.Windows.Forms.Application.ApplicationExit += new EventHandler(HandleQuit);
				//HelpMenu.MenuItems.Add(new CodeFileMenuItem("Release notes for this version", Meta.Installation.HelpFilePath("Release notes.meta")));
				HelpMenu.MenuItems.Add(0, new HelpDirectoryMenuItem("Packages", Meta.Installation.installDirectory+"\\Packages"));
				HelpMenu.MenuItems.Add(new Meta.HelpMenuItem("Programming environment",
					Meta.Installation.HelpFilePath("Programming environment.htm"),
					System.Windows.Forms.Shortcut.F1));
				HelpMenu.MenuItems.Add(new Meta.HelpMenuItem("Language reference manual", Meta.Installation.HelpFilePath("Meta language.htm")));
				HelpMenu.MenuItems.Add(new Meta.HelpMenuItem("Introduction for Scheme programmers", Meta.Installation.HelpFilePath("Meta for Scheme programmers.htm")));
				HelpMenu.MenuItems.Add(new Meta.HelpMenuItem("Release notes", Meta.Installation.HelpFilePath("Release notes.htm")));
				HelpMenu.MenuItems.Add(new Meta.HelpMenuItem("Implementation notes", Meta.Installation.HelpFilePath("Implementation notes.htm")));
				
				new StaticFlagMenuItem(editorSubmenu, "Switch to interaction window on eval", "Listener", "focusOnWrite");
				new StaticFlagMenuItem(editorSubmenu, "Insert matching brackets", "Editor", "insertMatchingBrackets");
				//new StaticFlagMenuItem(editorSubmenu, "Indent definitions LISP style", "Editor", "indentDefsLispStyle");
				new StaticFlagMenuItem(debugSubmenu, "Show &All expressions in debugger", "EvalStack", "showAllExpressions");
				new StaticFlagMenuItem(advancedMenu, "Always use Basic2D graphics package", "TopLevel", "AlwaysOpen2D");
				//code.BackColor = defaultBackgroundColor;
				ShowNamespace();
				fKeyMenuItem.MenuItems.AddRange(new MenuItem[] {
																   // new FKeyMenuItem(Shortcut.F1),   // don't want to shadow the help key
																   new FKeyMenuItem(Shortcut.F2),
																   new FKeyMenuItem(Shortcut.F3),
																   new FKeyMenuItem(Shortcut.F4),
																   new FKeyMenuItem(Shortcut.F5),
																   new FKeyMenuItem(Shortcut.F6),
																   new FKeyMenuItem(Shortcut.F7),
																   new FKeyMenuItem(Shortcut.F8),
																   new FKeyMenuItem(Shortcut.F9),
																   new FKeyMenuItem(Shortcut.F10),
																   new FKeyMenuItem(Shortcut.F11),
																   new FKeyMenuItem(Shortcut.F12)
															   });
				FKeyMenuItem_Popup(null, null);
				AddToEditorTable();
			}
		}

		static Editor() {
			Meta.Namespace.CurrentNamespaceChanged += new VoidThunk(NotePackage);
			Meta.TopLevel.idle += new VoidThunk(UpdateFKeyMenus);
			Meta.TopLevel.WarningsChanged += new Meta.TopLevel.WarningHandler(UpdateAllCheckMenus);
			Meta.EvalStack.Dump += new Meta.EvalStack.DumpHandler(DumpEditors);
		}

		static void UpdateFKeyMenus() {
			foreach (DictionaryEntry entry in editorTable) {
				if (entry.Value != null)
					((Editor)entry.Value).FKeyMenuItem_Popup(null, null);
			}
		}

		public Editor() {
			code = new CodeBox();
			fileToken = new FileToken();
			InitializeComponent();
			EditorInit();
			code.BackColor = defaultBackgroundColor;
			code.SetRegionStyle(new Region(0, code.TextLength), code.TheStyle("Normal"));
			Text = Name ="Untitled";
			UpdateCheckMenuStatus();
		}

		public Editor(string name, string contents) : this() {
			this.Name = name;
			this.code.Rtf = contents;
			ClearModified();
		}

		public Editor(string fullPathName) : this(FileToken.GetToken(fullPathName)) {
		}

		public Editor(FileToken fileToken) {
			this.fileToken = fileToken;
			string fileName = fileToken.Path;

			code = new CodeBox();
			InitializeComponent();
			if (System.IO.File.Exists(fileName)) {
				FileName = fileName;
				try {
					if (Path.GetExtension(fileName)==".scm") {
						MessageBox.Show("File will be converted to .meta format", "Open scheme file");
						code.LoadFile(fileName, RichTextBoxStreamType.PlainText);
						saveFileName = FileName = Path.ChangeExtension(fileName, ".meta");
					} else {
						// Kluge - turn off undo for really big files.
						System.IO.FileStream f  = System.IO.File.Open(fileName,System.IO.FileMode.Open,System.IO.FileAccess.Read);
						if (f.Length>50000)
							code.undoEnabled = false;

						// Check for header
						string header = "{\\*\\metaConfig";
						byte[] headerBuffer = new Byte[header.Length];
						char[] usableHeader = new Char[header.Length];
						f.Read(headerBuffer, 0, headerBuffer.Length);
						headerBuffer.CopyTo(usableHeader,0);
						bool hasConfigInfo = new String(usableHeader)==header;
						if (hasConfigInfo) {
							StreamReader reader = new StreamReader(f);
							object[] configInfo = (object[])(new Reader(reader, 0).Read());
							foreach (object[] config in configInfo) {
								object head = config[0];
								if (head==Symbol.Intern("styles")) {
									for (int style=1; style<config.Length; style++)
										code.RegisterStyle("foo", null); // config[style]);
								} // else unrecognized configuration parameter - ignore.
							}
							reader.Close();
						}
						f.Close();
						//code.LoadFile(f, RichTextBoxStreamType.RichText);
						code.LoadFile(saveFileName, RichTextBoxStreamType.RichText);
					}
				} catch (Exception e) {
					MessageBox.Show("An exception ocurred while trying to read the file.  Are you sure it's a Meta file?", "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					Meta.Inspector.Inspect(e);
				}
			} else {
				MessageBox.Show("Couldn't find the file "+fileName, "Error opening file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				Text = Name ="Untitled";
			}
			ClearModified();
			code.reIndent = false;
			EditorInit();
		}

		public string FileName {
			get {
				return saveFileName;
			}
			set {
				RemoveFromEditorTable();
				//Name = Path.GetFileName(value);
				Text = Name = Path.GetFileName(value);
				string path = Path.GetFullPath(value);
				saveFileName = path;
				fileToken.Path = path;
				AddToEditorTable();
			}
		}

		public Namespace Namespace {
			get {
				Namespace ns = FileNamespace(fileToken);
				return ns==null?Namespace.CurrentNamespace:ns;
			}
		}

		public void ShowNamespace() {
			SetValueText("Namespace: "+this.Namespace.ToString());
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing ) {
			System.Windows.Forms.Application.ApplicationExit -= new EventHandler(HandleQuit);
			// At one point, this seemed necessary to keep it from throwing an exception when closing an editor window.
			// code.Clear();
			if( disposing ) {
				if (components != null) {
					components.Dispose();
				}
			}
			RemoveFromEditorTable();
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Editor));
			this.mainMenu = new System.Windows.Forms.MainMenu();
			this.File = new System.Windows.Forms.MenuItem();
			this.FileNew = new System.Windows.Forms.MenuItem();
			this.FileOpen = new System.Windows.Forms.MenuItem();
			this.FileClose = new System.Windows.Forms.MenuItem();
			this.fileSeparator1 = new System.Windows.Forms.MenuItem();
			this.FileSave = new System.Windows.Forms.MenuItem();
			this.FileSaveAs = new System.Windows.Forms.MenuItem();
			this.setDefaultMenuItem = new System.Windows.Forms.MenuItem();
			this.fileSeparator2 = new System.Windows.Forms.MenuItem();
			this.FilePrint = new System.Windows.Forms.MenuItem();
			this.PreviewMenu = new System.Windows.Forms.MenuItem();
			this.PrinterSettingsMenu = new System.Windows.Forms.MenuItem();
			this.fileSeparator3 = new System.Windows.Forms.MenuItem();
			this.FileExit = new System.Windows.Forms.MenuItem();
			this.Edit = new System.Windows.Forms.MenuItem();
			this.undoMenuItem = new System.Windows.Forms.MenuItem();
			this.editSeparator1 = new System.Windows.Forms.MenuItem();
			this.Cut = new System.Windows.Forms.MenuItem();
			this.Copy = new System.Windows.Forms.MenuItem();
			this.Paste = new System.Windows.Forms.MenuItem();
			this.SelectAll = new System.Windows.Forms.MenuItem();
			this.editSeparator2 = new System.Windows.Forms.MenuItem();
			this.transposeMenuItem = new System.Windows.Forms.MenuItem();
			this.editSeparator3 = new System.Windows.Forms.MenuItem();
			this.pasteCommandMenuItem = new System.Windows.Forms.MenuItem();
			this.pasteNextCommandMenuItem = new System.Windows.Forms.MenuItem();
			this.menuItem5 = new System.Windows.Forms.MenuItem();
			this.findUnbalancedMenuItem = new System.Windows.Forms.MenuItem();
			this.editSeparator4 = new System.Windows.Forms.MenuItem();
			this.ISearchMenuItem = new System.Windows.Forms.MenuItem();
			this.findMenuItem = new System.Windows.Forms.MenuItem();
			this.ReplaceMenuItem = new System.Windows.Forms.MenuItem();
			this.menuItem6 = new System.Windows.Forms.MenuItem();
			this.FindDefinitionMenuItem = new System.Windows.Forms.MenuItem();
			this.ShowReferencesMenuItem = new System.Windows.Forms.MenuItem();
			this.ShowReferencesMenuItem2 = new System.Windows.Forms.MenuItem();
			this.formatMenu = new System.Windows.Forms.MenuItem();
			this.fontMenuItem = new System.Windows.Forms.MenuItem();
			this.formatSeparator1 = new System.Windows.Forms.MenuItem();
			this.formatBold = new System.Windows.Forms.MenuItem();
			this.formatItalic = new System.Windows.Forms.MenuItem();
			this.formatBullet = new System.Windows.Forms.MenuItem();
			this.formatSeparator2 = new System.Windows.Forms.MenuItem();
			this.formatGrow = new System.Windows.Forms.MenuItem();
			this.formatShrink = new System.Windows.Forms.MenuItem();
			this.formatSeparator3 = new System.Windows.Forms.MenuItem();
			this.formatSubscript = new System.Windows.Forms.MenuItem();
			this.formatSuperscript = new System.Windows.Forms.MenuItem();
			this.formatSeparator4 = new System.Windows.Forms.MenuItem();
			this.backgroundColorMenuItem = new System.Windows.Forms.MenuItem();
			this.reindentMenuItem = new System.Windows.Forms.MenuItem();
			this.reindentAllMenuItem = new System.Windows.Forms.MenuItem();
			this.RemoveWhitespaceMenuItem = new System.Windows.Forms.MenuItem();
			this.styleMenu = new System.Windows.Forms.MenuItem();
			this.editStylesMenuItem = new System.Windows.Forms.MenuItem();
			this.styleSeparator1 = new System.Windows.Forms.MenuItem();
			this.NormalStyleMenuItem = new System.Windows.Forms.MenuItem();
			this.TitleStyleMenuItem = new System.Windows.Forms.MenuItem();
			this.CommentStyleMenuItem = new System.Windows.Forms.MenuItem();
			this.menuItem2 = new System.Windows.Forms.MenuItem();
			this.restyleMenuItem = new System.Windows.Forms.MenuItem();
			this.restyleAllMenuItem = new System.Windows.Forms.MenuItem();
			this.restyleAllPreservingCommentsMenuItem = new System.Windows.Forms.MenuItem();
			this.Execute = new System.Windows.Forms.MenuItem();
			this.Evaluate = new System.Windows.Forms.MenuItem();
			this.inspectMenuItem = new System.Windows.Forms.MenuItem();
			this.executeSelectionMenuItem = new System.Windows.Forms.MenuItem();
			this.executeAllMenuItem = new System.Windows.Forms.MenuItem();
			this.SingleStepMenuItem = new System.Windows.Forms.MenuItem();
			this.continueExecutionMenuItem = new System.Windows.Forms.MenuItem();
			this.executeSeparator1 = new System.Windows.Forms.MenuItem();
			this.loadMenuItem = new System.Windows.Forms.MenuItem();
			this.executeSeparator2 = new System.Windows.Forms.MenuItem();
			this.InterruptExecution = new System.Windows.Forms.MenuItem();
			this.StopExec = new System.Windows.Forms.MenuItem();
			this.menuItem3 = new System.Windows.Forms.MenuItem();
			this.breakpointMenuItem = new System.Windows.Forms.MenuItem();
			this.breakpointExpressionMenuItem = new System.Windows.Forms.MenuItem();
			this.clearAllBreakpointsMenuItem = new System.Windows.Forms.MenuItem();
			this.menuItem1 = new System.Windows.Forms.MenuItem();
			this.traceMenuItem = new System.Windows.Forms.MenuItem();
			this.clearAllTracesMenuItem = new System.Windows.Forms.MenuItem();
			this.menuItem4 = new System.Windows.Forms.MenuItem();
			this.traceLoadMenuItem = new System.Windows.Forms.MenuItem();
			this.fKeyMenuItem = new System.Windows.Forms.MenuItem();
			this.advancedMenu = new System.Windows.Forms.MenuItem();
			this.beginnerModeMenuItem = new System.Windows.Forms.MenuItem();
			this.tailRecursionMenu = new System.Windows.Forms.MenuItem();
			this.fullTailRecursionMenuItem = new System.Windows.Forms.MenuItem();
			this.selfTailRecursionMenuItem = new System.Windows.Forms.MenuItem();
			this.noTailRecursionMenuItem = new System.Windows.Forms.MenuItem();
			this.debugSubmenu = new System.Windows.Forms.MenuItem();
			this.showDetailMenuItem = new System.Windows.Forms.MenuItem();
			this.editorSubmenu = new System.Windows.Forms.MenuItem();
			this.speedUpEditorMenuItem = new System.Windows.Forms.MenuItem();
			this.wizardSubmenu = new System.Windows.Forms.MenuItem();
			this.lowLevelDebugMenuItem = new System.Windows.Forms.MenuItem();
			this.forceGCMenuItem = new System.Windows.Forms.MenuItem();
			this.windowsMenu = new System.Windows.Forms.MenuItem();
			this.zoomMenu = new System.Windows.Forms.MenuItem();
			this.zoom300 = new System.Windows.Forms.MenuItem();
			this.zoom200 = new System.Windows.Forms.MenuItem();
			this.zoom150 = new System.Windows.Forms.MenuItem();
			this.zoom120 = new System.Windows.Forms.MenuItem();
			this.zoom110 = new System.Windows.Forms.MenuItem();
			this.zoom100 = new System.Windows.Forms.MenuItem();
			this.zoom90 = new System.Windows.Forms.MenuItem();
			this.zoom80 = new System.Windows.Forms.MenuItem();
			this.RecenterMenuItem = new System.Windows.Forms.MenuItem();
			this.GotoMenuItem = new System.Windows.Forms.MenuItem();
			this.HelpMenu = new System.Windows.Forms.MenuItem();
			this.examplesMenuItem = new System.Windows.Forms.MenuItem();
			this.searchMenuItem = new System.Windows.Forms.MenuItem();
			this.helpSeparator1 = new System.Windows.Forms.MenuItem();
			this.CheckMenu = new System.Windows.Forms.MenuItem();
			this.CheckMenuItem = new System.Windows.Forms.MenuItem();
			this.AutoCheckMenuItem = new System.Windows.Forms.MenuItem();
			this.printDialog1 = new System.Windows.Forms.PrintDialog();
			this.statusBar = new System.Windows.Forms.StatusBar();
			this.valuePanel = new System.Windows.Forms.StatusBarPanel();
			this.arglistPanel = new System.Windows.Forms.StatusBarPanel();
			this.contextMenu = new System.Windows.Forms.ContextMenu();
			this.contextCut = new System.Windows.Forms.MenuItem();
			this.contextCopy = new System.Windows.Forms.MenuItem();
			this.contextPaste = new System.Windows.Forms.MenuItem();
			this.contextSeparator1 = new System.Windows.Forms.MenuItem();
			this.contextExecute = new System.Windows.Forms.MenuItem();
			this.contextSingleStep = new System.Windows.Forms.MenuItem();
			this.contextInspect = new System.Windows.Forms.MenuItem();
			this.contextContinueExecutionMenuItem = new System.Windows.Forms.MenuItem();
			this.contextSeparator2 = new System.Windows.Forms.MenuItem();
			this.contextTrace = new System.Windows.Forms.MenuItem();
			this.contextBreakpoint = new System.Windows.Forms.MenuItem();
			this.contextBreakpointExpressionMenuItem = new System.Windows.Forms.MenuItem();
			this.contextSeparator3 = new System.Windows.Forms.MenuItem();
			this.contextFindDefinition = new System.Windows.Forms.MenuItem();
			this.traceAnalysisMenuItem = new System.Windows.Forms.MenuItem();
			this.menuItem7 = new System.Windows.Forms.MenuItem();
			this.contextFindUsesMenuItem = new System.Windows.Forms.MenuItem();
			((System.ComponentModel.ISupportInitialize)(this.valuePanel)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.arglistPanel)).BeginInit();
			this.SuspendLayout();
			// 
			// mainMenu
			// 
			this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.File,
																					 this.Edit,
																					 this.formatMenu,
																					 this.styleMenu,
																					 this.Execute,
																					 this.fKeyMenuItem,
																					 this.advancedMenu,
																					 this.windowsMenu,
																					 this.GotoMenuItem,
																					 this.HelpMenu,
																					 this.CheckMenu});
			// 
			// File
			// 
			this.File.Index = 0;
			this.File.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																				 this.FileNew,
																				 this.FileOpen,
																				 this.FileClose,
																				 this.fileSeparator1,
																				 this.FileSave,
																				 this.FileSaveAs,
																				 this.setDefaultMenuItem,
																				 this.fileSeparator2,
																				 this.FilePrint,
																				 this.PreviewMenu,
																				 this.PrinterSettingsMenu,
																				 this.fileSeparator3,
																				 this.FileExit});
			this.File.Text = "&File";
			// 
			// FileNew
			// 
			this.FileNew.Index = 0;
			this.FileNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
			this.FileNew.Text = "&New";
			this.FileNew.Click += new System.EventHandler(this.FileNew_Click);
			// 
			// FileOpen
			// 
			this.FileOpen.Index = 1;
			this.FileOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
			this.FileOpen.Text = "&Open";
			this.FileOpen.Click += new System.EventHandler(this.FileOpen_Click);
			// 
			// FileClose
			// 
			this.FileClose.Index = 2;
			this.FileClose.Text = "Close";
			this.FileClose.Click += new System.EventHandler(this.FileClose_Click);
			// 
			// fileSeparator1
			// 
			this.fileSeparator1.Index = 3;
			this.fileSeparator1.Text = "-";
			// 
			// FileSave
			// 
			this.FileSave.Index = 4;
			this.FileSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
			this.FileSave.Text = "&Save";
			this.FileSave.Click += new System.EventHandler(this.FileSave_Click);
			// 
			// FileSaveAs
			// 
			this.FileSaveAs.Index = 5;
			this.FileSaveAs.Text = "Save As...";
			this.FileSaveAs.Click += new System.EventHandler(this.FileSaveAs_Click);
			// 
			// setDefaultMenuItem
			// 
			this.setDefaultMenuItem.Index = 6;
			this.setDefaultMenuItem.Text = "Save as default settings";
			this.setDefaultMenuItem.Click += new System.EventHandler(this.setDefaultMenuItem_Click);
			// 
			// fileSeparator2
			// 
			this.fileSeparator2.Index = 7;
			this.fileSeparator2.Text = "-";
			// 
			// FilePrint
			// 
			this.FilePrint.Index = 8;
			this.FilePrint.Shortcut = System.Windows.Forms.Shortcut.CtrlP;
			this.FilePrint.Text = "&Print ...";
			this.FilePrint.Click += new System.EventHandler(this.FilePrint_Click);
			// 
			// PreviewMenu
			// 
			this.PreviewMenu.Index = 9;
			this.PreviewMenu.Text = "Print Preview";
			this.PreviewMenu.Click += new System.EventHandler(this.PreviewMenu_Click);
			// 
			// PrinterSettingsMenu
			// 
			this.PrinterSettingsMenu.Index = 10;
			this.PrinterSettingsMenu.Text = "Printer Settings";
			this.PrinterSettingsMenu.Click += new System.EventHandler(this.PrinterSettingsMenu_Click);
			// 
			// fileSeparator3
			// 
			this.fileSeparator3.Index = 11;
			this.fileSeparator3.Text = "-";
			// 
			// FileExit
			// 
			this.FileExit.Index = 12;
			this.FileExit.Text = "E&xit";
			this.FileExit.Click += new System.EventHandler(this.FileExit_Click);
			// 
			// Edit
			// 
			this.Edit.Index = 1;
			this.Edit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																				 this.undoMenuItem,
																				 this.editSeparator1,
																				 this.Cut,
																				 this.Copy,
																				 this.Paste,
																				 this.SelectAll,
																				 this.editSeparator2,
																				 this.transposeMenuItem,
																				 this.editSeparator3,
																				 this.pasteCommandMenuItem,
																				 this.pasteNextCommandMenuItem,
																				 this.menuItem5,
																				 this.findUnbalancedMenuItem,
																				 this.editSeparator4,
																				 this.ISearchMenuItem,
																				 this.findMenuItem,
																				 this.ReplaceMenuItem,
																				 this.menuItem6,
																				 this.FindDefinitionMenuItem,
																				 this.ShowReferencesMenuItem,
																				 this.ShowReferencesMenuItem2});
			this.Edit.Text = "&Edit";
			this.Edit.Popup += new System.EventHandler(this.EditMenu_Pop);
			// 
			// undoMenuItem
			// 
			this.undoMenuItem.Index = 0;
			this.undoMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlZ;
			this.undoMenuItem.Text = "Undo";
			this.undoMenuItem.Click += new System.EventHandler(this.Undo_Click);
			// 
			// editSeparator1
			// 
			this.editSeparator1.Index = 1;
			this.editSeparator1.Text = "-";
			// 
			// Cut
			// 
			this.Cut.Index = 2;
			this.Cut.Shortcut = System.Windows.Forms.Shortcut.CtrlX;
			this.Cut.Text = "Cut";
			this.Cut.Click += new System.EventHandler(this.Cut_Click);
			// 
			// Copy
			// 
			this.Copy.Index = 3;
			this.Copy.Shortcut = System.Windows.Forms.Shortcut.CtrlC;
			this.Copy.Text = "Copy";
			this.Copy.Click += new System.EventHandler(this.Copy_Click);
			// 
			// Paste
			// 
			this.Paste.Index = 4;
			this.Paste.Shortcut = System.Windows.Forms.Shortcut.CtrlV;
			this.Paste.Text = "Paste";
			this.Paste.Click += new System.EventHandler(this.Paste_Click);
			// 
			// SelectAll
			// 
			this.SelectAll.Index = 5;
			this.SelectAll.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
			this.SelectAll.Text = "Select &All";
			this.SelectAll.Click += new System.EventHandler(this.SelectAll_Click);
			// 
			// editSeparator2
			// 
			this.editSeparator2.Index = 6;
			this.editSeparator2.Text = "-";
			// 
			// transposeMenuItem
			// 
			this.transposeMenuItem.Index = 7;
			this.transposeMenuItem.Text = "Transpose expressions (Ctrl-Alt-T)";
			this.transposeMenuItem.Click += new System.EventHandler(this.Transpose_Click);
			// 
			// editSeparator3
			// 
			this.editSeparator3.Index = 8;
			this.editSeparator3.Text = "-";
			// 
			// pasteCommandMenuItem
			// 
			this.pasteCommandMenuItem.Index = 9;
			this.pasteCommandMenuItem.Text = "Paste &Previous command";
			this.pasteCommandMenuItem.Click += new System.EventHandler(this.pasteCommandMenuItem_Click);
			// 
			// pasteNextCommandMenuItem
			// 
			this.pasteNextCommandMenuItem.Index = 10;
			this.pasteNextCommandMenuItem.Text = "Paste &Next command";
			this.pasteNextCommandMenuItem.Click += new System.EventHandler(this.menuItem8_Click);
			// 
			// menuItem5
			// 
			this.menuItem5.Index = 11;
			this.menuItem5.Text = "-";
			// 
			// findUnbalancedMenuItem
			// 
			this.findUnbalancedMenuItem.Index = 12;
			this.findUnbalancedMenuItem.Text = "Find &unbalanced brackets";
			this.findUnbalancedMenuItem.Click += new System.EventHandler(this.ReindentAllMenuItem_Click);
			// 
			// editSeparator4
			// 
			this.editSeparator4.Index = 13;
			this.editSeparator4.Text = "-";
			this.editSeparator4.Click += new System.EventHandler(this.Transpose_Click);
			// 
			// ISearchMenuItem
			// 
			this.ISearchMenuItem.Index = 14;
			this.ISearchMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlShiftS;
			this.ISearchMenuItem.Text = "&Incremental search ...";
			this.ISearchMenuItem.Click += new System.EventHandler(this.ISearchMenuItem_Click);
			// 
			// findMenuItem
			// 
			this.findMenuItem.Index = 15;
			this.findMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF;
			this.findMenuItem.Text = "&Find ...";
			this.findMenuItem.Click += new System.EventHandler(this.findMenuItem_Click);
			// 
			// ReplaceMenuItem
			// 
			this.ReplaceMenuItem.Index = 16;
			this.ReplaceMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlH;
			this.ReplaceMenuItem.Text = "&Replace ...";
			this.ReplaceMenuItem.Click += new System.EventHandler(this.ReplaceMenuItem_Click);
			// 
			// menuItem6
			// 
			this.menuItem6.Index = 17;
			this.menuItem6.Text = "-";
			// 
			// FindDefinitionMenuItem
			// 
			this.FindDefinitionMenuItem.Index = 18;
			this.FindDefinitionMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlD;
			this.FindDefinitionMenuItem.Text = "Find &Definition";
			this.FindDefinitionMenuItem.Click += new System.EventHandler(this.FindDefinition_Click);
			// 
			// ShowReferencesMenuItem
			// 
			this.ShowReferencesMenuItem.Index = 19;
			this.ShowReferencesMenuItem.Text = "&Show references";
			this.ShowReferencesMenuItem.Click += new System.EventHandler(this.ShowReferences_Click);
			// 
			// ShowReferencesMenuItem2
			// 
			this.ShowReferencesMenuItem2.Index = 20;
			this.ShowReferencesMenuItem2.Text = "Show &references";
			this.ShowReferencesMenuItem2.Click += new System.EventHandler(this.ShowReferences2_Click);
			// 
			// formatMenu
			// 
			this.formatMenu.Index = 2;
			this.formatMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					   this.fontMenuItem,
																					   this.formatSeparator1,
																					   this.formatBold,
																					   this.formatItalic,
																					   this.formatBullet,
																					   this.formatSeparator2,
																					   this.formatGrow,
																					   this.formatShrink,
																					   this.formatSeparator3,
																					   this.formatSubscript,
																					   this.formatSuperscript,
																					   this.formatSeparator4,
																					   this.backgroundColorMenuItem,
																					   this.reindentMenuItem,
																					   this.reindentAllMenuItem,
																					   this.RemoveWhitespaceMenuItem});
			this.formatMenu.Text = "F&ormat";
			this.formatMenu.Popup += new System.EventHandler(this.FormatMenuPop);
			// 
			// fontMenuItem
			// 
			this.fontMenuItem.Index = 0;
			this.fontMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlShiftF;
			this.fontMenuItem.Text = "&Font ...";
			this.fontMenuItem.Click += new System.EventHandler(this.Font_Click);
			// 
			// formatSeparator1
			// 
			this.formatSeparator1.Index = 1;
			this.formatSeparator1.Text = "-";
			// 
			// formatBold
			// 
			this.formatBold.Index = 2;
			this.formatBold.Shortcut = System.Windows.Forms.Shortcut.CtrlB;
			this.formatBold.Text = "&Bold";
			this.formatBold.Click += new System.EventHandler(this.FormatBoldClick);
			// 
			// formatItalic
			// 
			this.formatItalic.Index = 3;
			this.formatItalic.Shortcut = System.Windows.Forms.Shortcut.CtrlI;
			this.formatItalic.Text = "&Italic";
			this.formatItalic.Click += new System.EventHandler(this.FormatItalicClick);
			// 
			// formatBullet
			// 
			this.formatBullet.Index = 4;
			this.formatBullet.Shortcut = System.Windows.Forms.Shortcut.CtrlShiftL;
			this.formatBullet.Text = "Bullet";
			this.formatBullet.Click += new System.EventHandler(this.FormatBulletClick);
			// 
			// formatSeparator2
			// 
			this.formatSeparator2.Index = 5;
			this.formatSeparator2.Text = "-";
			// 
			// formatGrow
			// 
			this.formatGrow.Index = 6;
			this.formatGrow.Text = "Grow font";
			this.formatGrow.Click += new System.EventHandler(this.FormatGrowClick);
			// 
			// formatShrink
			// 
			this.formatShrink.Index = 7;
			this.formatShrink.Text = "Shrink font";
			this.formatShrink.Click += new System.EventHandler(this.FormatShrinkClick);
			// 
			// formatSeparator3
			// 
			this.formatSeparator3.Index = 8;
			this.formatSeparator3.Text = "-";
			// 
			// formatSubscript
			// 
			this.formatSubscript.Index = 9;
			this.formatSubscript.Text = "Superscript";
			this.formatSubscript.Click += new System.EventHandler(this.FormatSuperscriptClick);
			// 
			// formatSuperscript
			// 
			this.formatSuperscript.Index = 10;
			this.formatSuperscript.Text = "Subscript";
			this.formatSuperscript.Click += new System.EventHandler(this.FormatSubscriptClick);
			// 
			// formatSeparator4
			// 
			this.formatSeparator4.Index = 11;
			this.formatSeparator4.Text = "-";
			// 
			// backgroundColorMenuItem
			// 
			this.backgroundColorMenuItem.Index = 12;
			this.backgroundColorMenuItem.Text = "Background &color ...";
			this.backgroundColorMenuItem.Click += new System.EventHandler(this.backgroundColorMenuItem_Click);
			// 
			// reindentMenuItem
			// 
			this.reindentMenuItem.Index = 13;
			this.reindentMenuItem.Text = "&Reindent";
			this.reindentMenuItem.Click += new System.EventHandler(this.ReindentMenuItem_Click);
			// 
			// reindentAllMenuItem
			// 
			this.reindentAllMenuItem.Index = 14;
			this.reindentAllMenuItem.Text = "Reindent &all";
			this.reindentAllMenuItem.Click += new System.EventHandler(this.ReindentAllMenuItem_Click);
			// 
			// RemoveWhitespaceMenuItem
			// 
			this.RemoveWhitespaceMenuItem.Index = 15;
			this.RemoveWhitespaceMenuItem.Text = "Remove &Leading whitespace";
			this.RemoveWhitespaceMenuItem.Click += new System.EventHandler(this.RemoveWhitespaceMenuItem_Click);
			// 
			// styleMenu
			// 
			this.styleMenu.Index = 3;
			this.styleMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.editStylesMenuItem,
																					  this.styleSeparator1,
																					  this.NormalStyleMenuItem,
																					  this.TitleStyleMenuItem,
																					  this.CommentStyleMenuItem,
																					  this.menuItem2,
																					  this.restyleMenuItem,
																					  this.restyleAllMenuItem,
																					  this.restyleAllPreservingCommentsMenuItem});
			this.styleMenu.Text = "&Style";
			// 
			// editStylesMenuItem
			// 
			this.editStylesMenuItem.Index = 0;
			this.editStylesMenuItem.Text = "Edit styles";
			this.editStylesMenuItem.Click += new System.EventHandler(this.EditStyles_Click);
			// 
			// styleSeparator1
			// 
			this.styleSeparator1.Index = 1;
			this.styleSeparator1.Text = "-";
			// 
			// NormalStyleMenuItem
			// 
			this.NormalStyleMenuItem.Index = 2;
			this.NormalStyleMenuItem.Text = "&Normal";
			this.NormalStyleMenuItem.Click += new System.EventHandler(this.ApplyStyle);
			// 
			// TitleStyleMenuItem
			// 
			this.TitleStyleMenuItem.Index = 3;
			this.TitleStyleMenuItem.Text = "&Title";
			this.TitleStyleMenuItem.Click += new System.EventHandler(this.ApplyStyle);
			// 
			// CommentStyleMenuItem
			// 
			this.CommentStyleMenuItem.Index = 4;
			this.CommentStyleMenuItem.Text = "&Comment";
			this.CommentStyleMenuItem.Click += new System.EventHandler(this.ApplyStyle);
			// 
			// menuItem2
			// 
			this.menuItem2.Index = 5;
			this.menuItem2.Text = "-";
			// 
			// restyleMenuItem
			// 
			this.restyleMenuItem.Index = 6;
			this.restyleMenuItem.Text = "&Restyle this expression";
			this.restyleMenuItem.Click += new System.EventHandler(this.restyleMenuItem_Click);
			// 
			// restyleAllMenuItem
			// 
			this.restyleAllMenuItem.Index = 7;
			this.restyleAllMenuItem.Text = "Restyle &all, including comments";
			this.restyleAllMenuItem.Click += new System.EventHandler(this.restyleAllMenuItem_Click);
			// 
			// restyleAllPreservingCommentsMenuItem
			// 
			this.restyleAllPreservingCommentsMenuItem.Index = 8;
			this.restyleAllPreservingCommentsMenuItem.Text = "Restyle all, &preserving comments";
			this.restyleAllPreservingCommentsMenuItem.Click += new System.EventHandler(this.restyleAllPreservingCommentsMenuItem_Click);
			// 
			// Execute
			// 
			this.Execute.Index = 4;
			this.Execute.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					this.Evaluate,
																					this.inspectMenuItem,
																					this.executeSelectionMenuItem,
																					this.executeAllMenuItem,
																					this.SingleStepMenuItem,
																					this.continueExecutionMenuItem,
																					this.executeSeparator1,
																					this.loadMenuItem,
																					this.executeSeparator2,
																					this.InterruptExecution,
																					this.StopExec,
																					this.menuItem3,
																					this.breakpointMenuItem,
																					this.breakpointExpressionMenuItem,
																					this.clearAllBreakpointsMenuItem,
																					this.menuItem1,
																					this.traceMenuItem,
																					this.clearAllTracesMenuItem,
																					this.menuItem4,
																					this.traceLoadMenuItem});
			this.Execute.Text = "E&xecute";
			this.Execute.Popup += new System.EventHandler(this.MenuPop_Execute);
			// 
			// Evaluate
			// 
			this.Evaluate.Index = 0;
			this.Evaluate.Shortcut = System.Windows.Forms.Shortcut.CtrlE;
			this.Evaluate.Text = "&Execute";
			this.Evaluate.Click += new System.EventHandler(this.Evaluate_Click);
			// 
			// inspectMenuItem
			// 
			this.inspectMenuItem.Index = 1;
			this.inspectMenuItem.Text = "Execute and &Inspect result";
			this.inspectMenuItem.Click += new System.EventHandler(this.Inspect_Click);
			// 
			// executeSelectionMenuItem
			// 
			this.executeSelectionMenuItem.Index = 2;
			this.executeSelectionMenuItem.Text = "Execute &Selection";
			this.executeSelectionMenuItem.Click += new System.EventHandler(this.EvalRegion_Click);
			// 
			// executeAllMenuItem
			// 
			this.executeAllMenuItem.Index = 3;
			this.executeAllMenuItem.Text = "Execute &All";
			this.executeAllMenuItem.Click += new System.EventHandler(this.EvalFile_Click);
			// 
			// SingleStepMenuItem
			// 
			this.SingleStepMenuItem.Index = 4;
			this.SingleStepMenuItem.Shortcut = System.Windows.Forms.Shortcut.Ctrl1;
			this.SingleStepMenuItem.Text = "Execute &1 Step";
			this.SingleStepMenuItem.Click += new System.EventHandler(this.SingleStep_Click);
			// 
			// continueExecutionMenuItem
			// 
			this.continueExecutionMenuItem.Index = 5;
			this.continueExecutionMenuItem.Shortcut = System.Windows.Forms.Shortcut.F12;
			this.continueExecutionMenuItem.Text = "&Continue execution to here";
			this.continueExecutionMenuItem.Click += new System.EventHandler(this.continueExecutionMenuItem_Click);
			// 
			// executeSeparator1
			// 
			this.executeSeparator1.Index = 6;
			this.executeSeparator1.Text = "-";
			// 
			// loadMenuItem
			// 
			this.loadMenuItem.Index = 7;
			this.loadMenuItem.Text = "Load file ...";
			this.loadMenuItem.Click += new System.EventHandler(this.loadMenuItem_Click);
			// 
			// executeSeparator2
			// 
			this.executeSeparator2.Index = 8;
			this.executeSeparator2.Text = "-";
			// 
			// InterruptExecution
			// 
			this.InterruptExecution.Index = 9;
			this.InterruptExecution.Text = "Interrupt execution";
			this.InterruptExecution.Click += new System.EventHandler(this.InterruptExecution_Click);
			// 
			// StopExec
			// 
			this.StopExec.Index = 10;
			this.StopExec.Shortcut = System.Windows.Forms.Shortcut.CtrlDel;
			this.StopExec.Text = "Abort execution";
			this.StopExec.Click += new System.EventHandler(this.StopExec_Click);
			// 
			// menuItem3
			// 
			this.menuItem3.Index = 11;
			this.menuItem3.Text = "-";
			// 
			// breakpointMenuItem
			// 
			this.breakpointMenuItem.Index = 12;
			this.breakpointMenuItem.Shortcut = System.Windows.Forms.Shortcut.ShiftDel;
			this.breakpointMenuItem.Text = "Breakpoint procedure";
			this.breakpointMenuItem.Click += new System.EventHandler(this.Breakpoint_Click);
			// 
			// breakpointExpressionMenuItem
			// 
			this.breakpointExpressionMenuItem.Index = 13;
			this.breakpointExpressionMenuItem.Text = "Breakpoint expression";
			this.breakpointExpressionMenuItem.Click += new System.EventHandler(this.breakpointExpressionMenuItem_Click);
			// 
			// clearAllBreakpointsMenuItem
			// 
			this.clearAllBreakpointsMenuItem.Index = 14;
			this.clearAllBreakpointsMenuItem.Text = "Clear all breakpoints";
			this.clearAllBreakpointsMenuItem.Click += new System.EventHandler(this.clearAllBreakpointsMenuItem_Click);
			// 
			// menuItem1
			// 
			this.menuItem1.Index = 15;
			this.menuItem1.Text = "-";
			// 
			// traceMenuItem
			// 
			this.traceMenuItem.Index = 16;
			this.traceMenuItem.Text = "&Trace procedure";
			this.traceMenuItem.Click += new System.EventHandler(this.Trace_Click);
			// 
			// clearAllTracesMenuItem
			// 
			this.clearAllTracesMenuItem.Index = 17;
			this.clearAllTracesMenuItem.Text = "Clear all traces";
			this.clearAllTracesMenuItem.Click += new System.EventHandler(this.clearAllTracesMenuItem_Click);
			// 
			// menuItem4
			// 
			this.menuItem4.Index = 18;
			this.menuItem4.Text = "-";
			// 
			// traceLoadMenuItem
			// 
			this.traceLoadMenuItem.Index = 19;
			this.traceLoadMenuItem.Text = "&Print all results when loading files";
			this.traceLoadMenuItem.Click += new System.EventHandler(this.traceLoadMenuItem_Click);
			// 
			// fKeyMenuItem
			// 
			this.fKeyMenuItem.Index = 5;
			this.fKeyMenuItem.Text = "Hot&keys";
			this.fKeyMenuItem.Popup += new System.EventHandler(this.FKeyMenuItem_Popup);
			// 
			// advancedMenu
			// 
			this.advancedMenu.Index = 6;
			this.advancedMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						 this.beginnerModeMenuItem,
																						 this.tailRecursionMenu,
																						 this.debugSubmenu,
																						 this.editorSubmenu,
																						 this.wizardSubmenu});
			this.advancedMenu.Text = "&Advanced";
			this.advancedMenu.Popup += new System.EventHandler(this.MenuPop_Advanced);
			// 
			// beginnerModeMenuItem
			// 
			this.beginnerModeMenuItem.Index = 0;
			this.beginnerModeMenuItem.Text = "Beginning programmer mode";
			this.beginnerModeMenuItem.Click += new System.EventHandler(this.beginnerModeMenuItem_Click);
			// 
			// tailRecursionMenu
			// 
			this.tailRecursionMenu.Index = 1;
			this.tailRecursionMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																							  this.fullTailRecursionMenuItem,
																							  this.selfTailRecursionMenuItem,
																							  this.noTailRecursionMenuItem});
			this.tailRecursionMenu.Text = "Tail recursion";
			this.tailRecursionMenu.Popup += new System.EventHandler(this.tailRecursionMenu_Popup);
			// 
			// fullTailRecursionMenuItem
			// 
			this.fullTailRecursionMenuItem.Index = 0;
			this.fullTailRecursionMenuItem.Text = "Full optimization";
			this.fullTailRecursionMenuItem.Click += new System.EventHandler(this.fullTailRecursionMenuItem_Click);
			// 
			// selfTailRecursionMenuItem
			// 
			this.selfTailRecursionMenuItem.Index = 1;
			this.selfTailRecursionMenuItem.Text = "Self-recursion only";
			this.selfTailRecursionMenuItem.Click += new System.EventHandler(this.selfTailRecursionMenuItem_Click);
			// 
			// noTailRecursionMenuItem
			// 
			this.noTailRecursionMenuItem.Index = 2;
			this.noTailRecursionMenuItem.Text = "No optimization";
			this.noTailRecursionMenuItem.Click += new System.EventHandler(this.noTailRecursionMenuItem_Click);
			// 
			// debugSubmenu
			// 
			this.debugSubmenu.Index = 2;
			this.debugSubmenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						 this.showDetailMenuItem});
			this.debugSubmenu.Text = "&Debug";
			// 
			// showDetailMenuItem
			// 
			this.showDetailMenuItem.Index = 0;
			this.showDetailMenuItem.Text = "Show &detail in inspector";
			this.showDetailMenuItem.Click += new System.EventHandler(this.ShowDetail_Click);
			// 
			// editorSubmenu
			// 
			this.editorSubmenu.Index = 3;
			this.editorSubmenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						  this.speedUpEditorMenuItem});
			this.editorSubmenu.Text = "&Editor";
			// 
			// speedUpEditorMenuItem
			// 
			this.speedUpEditorMenuItem.Index = 0;
			this.speedUpEditorMenuItem.Text = "&Speed up editor (turns off features)";
			this.speedUpEditorMenuItem.Click += new System.EventHandler(this.SpeedUpEditor_Click);
			// 
			// wizardSubmenu
			// 
			this.wizardSubmenu.Index = 4;
			this.wizardSubmenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						  this.lowLevelDebugMenuItem,
																						  this.forceGCMenuItem});
			this.wizardSubmenu.Text = "&Wizard";
			// 
			// lowLevelDebugMenuItem
			// 
			this.lowLevelDebugMenuItem.Index = 0;
			this.lowLevelDebugMenuItem.Text = "&Low level debug";
			this.lowLevelDebugMenuItem.Click += new System.EventHandler(this.LowLevel_Click);
			// 
			// forceGCMenuItem
			// 
			this.forceGCMenuItem.Index = 1;
			this.forceGCMenuItem.Text = "Force &GC";
			this.forceGCMenuItem.Click += new System.EventHandler(this.forceGCMenuItem_Click);
			// 
			// windowsMenu
			// 
			this.windowsMenu.Index = 7;
			this.windowsMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						this.zoomMenu,
																						this.RecenterMenuItem});
			this.windowsMenu.Text = "&Windows";
			this.windowsMenu.Popup += new System.EventHandler(this.windowsMenu_Select);
			this.windowsMenu.Select += new System.EventHandler(this.windowsMenu_Select);
			// 
			// zoomMenu
			// 
			this.zoomMenu.Index = 0;
			this.zoomMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.zoom300,
																					 this.zoom200,
																					 this.zoom150,
																					 this.zoom120,
																					 this.zoom110,
																					 this.zoom100,
																					 this.zoom90,
																					 this.zoom80});
			this.zoomMenu.Text = "&Zoom";
			this.zoomMenu.Popup += new System.EventHandler(this.zoomMenu_Popup);
			// 
			// zoom300
			// 
			this.zoom300.Index = 0;
			this.zoom300.Shortcut = System.Windows.Forms.Shortcut.CtrlShift3;
			this.zoom300.Text = "300%";
			this.zoom300.Click += new System.EventHandler(this.zoom300_Click);
			// 
			// zoom200
			// 
			this.zoom200.Index = 1;
			this.zoom200.Text = "200%";
			this.zoom200.Click += new System.EventHandler(this.zoom200_Click);
			// 
			// zoom150
			// 
			this.zoom150.Index = 2;
			this.zoom150.Shortcut = System.Windows.Forms.Shortcut.CtrlShiftF5;
			this.zoom150.Text = "150%";
			this.zoom150.Click += new System.EventHandler(this.zoom150_Click);
			// 
			// zoom120
			// 
			this.zoom120.Index = 3;
			this.zoom120.Shortcut = System.Windows.Forms.Shortcut.CtrlShift2;
			this.zoom120.Text = "120%";
			this.zoom120.Click += new System.EventHandler(this.zoom120_Click);
			// 
			// zoom110
			// 
			this.zoom110.Index = 4;
			this.zoom110.Shortcut = System.Windows.Forms.Shortcut.CtrlShift1;
			this.zoom110.Text = "110%";
			this.zoom110.Click += new System.EventHandler(this.zoom110_Click);
			// 
			// zoom100
			// 
			this.zoom100.Index = 5;
			this.zoom100.Shortcut = System.Windows.Forms.Shortcut.CtrlShift0;
			this.zoom100.Text = "100%";
			this.zoom100.Click += new System.EventHandler(this.zoom100_Click);
			// 
			// zoom90
			// 
			this.zoom90.Index = 6;
			this.zoom90.Shortcut = System.Windows.Forms.Shortcut.CtrlShift9;
			this.zoom90.Text = "90%";
			this.zoom90.Click += new System.EventHandler(this.zoom90_Click);
			// 
			// zoom80
			// 
			this.zoom80.Index = 7;
			this.zoom80.Shortcut = System.Windows.Forms.Shortcut.CtrlShift8;
			this.zoom80.Text = "80%";
			this.zoom80.Click += new System.EventHandler(this.zoom80_Click);
			// 
			// RecenterMenuItem
			// 
			this.RecenterMenuItem.Index = 1;
			this.RecenterMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlL;
			this.RecenterMenuItem.Text = "&Recenter";
			this.RecenterMenuItem.Click += new System.EventHandler(this.RecenterMenuItem_Click);
			// 
			// GotoMenuItem
			// 
			this.GotoMenuItem.Index = 8;
			this.GotoMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlShiftG;
			this.GotoMenuItem.Text = "&Definitions";
			this.GotoMenuItem.Popup += new System.EventHandler(this.GotoMenuItem_Pop);
			this.GotoMenuItem.Select += new System.EventHandler(this.GotoMenuItem_Pop);
			// 
			// HelpMenu
			// 
			this.HelpMenu.Index = 9;
			this.HelpMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					 this.examplesMenuItem,
																					 this.searchMenuItem,
																					 this.helpSeparator1});
			this.HelpMenu.Text = "&Help";
			// 
			// examplesMenuItem
			// 
			this.examplesMenuItem.Index = 0;
			this.examplesMenuItem.Text = "Examples ...";
			this.examplesMenuItem.Click += new System.EventHandler(this.examplesMenuItem_Click);
			// 
			// searchMenuItem
			// 
			this.searchMenuItem.Index = 1;
			this.searchMenuItem.Text = "Search ...";
			this.searchMenuItem.Click += new System.EventHandler(this.AproposClick);
			// 
			// helpSeparator1
			// 
			this.helpSeparator1.Index = 2;
			this.helpSeparator1.Text = "-";
			// 
			// CheckMenu
			// 
			this.CheckMenu.Index = 10;
			this.CheckMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.CheckMenuItem,
																					  this.AutoCheckMenuItem});
			this.CheckMenu.Text = "&Check";
			this.CheckMenu.Popup += new System.EventHandler(this.CheckMenu_Popup);
			// 
			// CheckMenuItem
			// 
			this.CheckMenuItem.Index = 0;
			this.CheckMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlF1;
			this.CheckMenuItem.Text = "&Check now";
			this.CheckMenuItem.Click += new System.EventHandler(this.CheckMenuItem_Click);
			// 
			// AutoCheckMenuItem
			// 
			this.AutoCheckMenuItem.Index = 1;
			this.AutoCheckMenuItem.Text = "Auto check";
			this.AutoCheckMenuItem.Click += new System.EventHandler(this.AutoCheckMenuItem_Click);
			// 
			// statusBar
			// 
			this.statusBar.Anchor = System.Windows.Forms.AnchorStyles.None;
			this.statusBar.Dock = System.Windows.Forms.DockStyle.None;
			this.statusBar.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.statusBar.Location = new System.Drawing.Point(0, 489);
			this.statusBar.Name = "statusBar";
			this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
																						 this.valuePanel,
																						 this.arglistPanel});
			this.statusBar.ShowPanels = true;
			this.statusBar.Size = new System.Drawing.Size(552, 20);
			this.statusBar.TabIndex = 0;
			this.statusBar.Text = "statusBar";
			// 
			// valuePanel
			// 
			this.valuePanel.MinWidth = 100;
			this.valuePanel.Width = 150;
			// 
			// arglistPanel
			// 
			this.arglistPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.arglistPanel.MinWidth = 200;
			this.arglistPanel.Width = 386;
			// 
			// contextMenu
			// 
			this.contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						this.contextCut,
																						this.contextCopy,
																						this.contextPaste,
																						this.contextSeparator1,
																						this.contextExecute,
																						this.contextSingleStep,
																						this.contextInspect,
																						this.contextContinueExecutionMenuItem,
																						this.contextSeparator2,
																						this.contextTrace,
																						this.contextBreakpoint,
																						this.contextBreakpointExpressionMenuItem,
																						this.menuItem7,
																						this.traceAnalysisMenuItem,
																						this.contextSeparator3,
																						this.contextFindDefinition,
																						this.contextFindUsesMenuItem});
			this.contextMenu.Popup += new System.EventHandler(this.contextMenu1_Popup);
			// 
			// contextCut
			// 
			this.contextCut.Index = 0;
			this.contextCut.Text = "Cut";
			this.contextCut.Click += new System.EventHandler(this.Cut_Click);
			// 
			// contextCopy
			// 
			this.contextCopy.Index = 1;
			this.contextCopy.Text = "Copy";
			this.contextCopy.Click += new System.EventHandler(this.Copy_Click);
			// 
			// contextPaste
			// 
			this.contextPaste.Index = 2;
			this.contextPaste.Text = "Paste";
			this.contextPaste.Click += new System.EventHandler(this.Paste_Click);
			// 
			// contextSeparator1
			// 
			this.contextSeparator1.Index = 3;
			this.contextSeparator1.Text = "-";
			// 
			// contextExecute
			// 
			this.contextExecute.Index = 4;
			this.contextExecute.Text = "Execute";
			this.contextExecute.Click += new System.EventHandler(this.Evaluate_Click);
			// 
			// contextSingleStep
			// 
			this.contextSingleStep.Index = 5;
			this.contextSingleStep.Text = "Execute 1 step";
			this.contextSingleStep.Click += new System.EventHandler(this.SingleStep_Click);
			// 
			// contextInspect
			// 
			this.contextInspect.Index = 6;
			this.contextInspect.Text = "Execute and inspect";
			this.contextInspect.Click += new System.EventHandler(this.Inspect_Click);
			// 
			// contextContinueExecutionMenuItem
			// 
			this.contextContinueExecutionMenuItem.Index = 7;
			this.contextContinueExecutionMenuItem.Text = "Continue execution to here";
			this.contextContinueExecutionMenuItem.Click += new System.EventHandler(this.continueExecutionMenuItem_Click);
			// 
			// contextSeparator2
			// 
			this.contextSeparator2.Index = 8;
			this.contextSeparator2.Text = "-";
			// 
			// contextTrace
			// 
			this.contextTrace.Index = 9;
			this.contextTrace.Text = "Trace Procedure";
			this.contextTrace.Click += new System.EventHandler(this.Trace_Click);
			// 
			// contextBreakpoint
			// 
			this.contextBreakpoint.Index = 10;
			this.contextBreakpoint.Text = "Breakpoint Procedure";
			this.contextBreakpoint.Click += new System.EventHandler(this.Breakpoint_Click);
			// 
			// contextBreakpointExpressionMenuItem
			// 
			this.contextBreakpointExpressionMenuItem.Index = 11;
			this.contextBreakpointExpressionMenuItem.Text = "Breakpoint Expression";
			this.contextBreakpointExpressionMenuItem.Click += new System.EventHandler(this.breakpointExpressionMenuItem_Click);
			// 
			// contextSeparator3
			// 
			this.contextSeparator3.Index = 14;
			this.contextSeparator3.Text = "-";
			// 
			// contextFindDefinition
			// 
			this.contextFindDefinition.Index = 15;
			this.contextFindDefinition.Text = "Find definition";
			this.contextFindDefinition.Click += new System.EventHandler(this.FindDefinition_Click);
			// 
			// traceAnalysisMenuItem
			// 
			this.traceAnalysisMenuItem.Index = 13;
			this.traceAnalysisMenuItem.Text = "Trace analysis";
			this.traceAnalysisMenuItem.Click += new System.EventHandler(this.traceAnalysisMenuItem_Click);
			// 
			// menuItem7
			// 
			this.menuItem7.Index = 12;
			this.menuItem7.Text = "-";
			// 
			// contextFindUsesMenuItem
			// 
			this.contextFindUsesMenuItem.Index = 16;
			this.contextFindUsesMenuItem.Text = "Find uses";
			this.contextFindUsesMenuItem.Click += new System.EventHandler(this.contextFindUsesMenuItem_Click);
			// 
			// Editor
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
			this.BackColor = System.Drawing.SystemColors.Control;
			this.ClientSize = new System.Drawing.Size(552, 365);
			this.Controls.Add(this.statusBar);
			this.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Menu = this.mainMenu;
			this.Name = "Editor";
			this.Text = "Untitled";
			((System.ComponentModel.ISupportInitialize)(this.valuePanel)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.arglistPanel)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		protected override void OnLayout(LayoutEventArgs e) {
			code.Size = new Size(ClientSize.Width, ClientSize.Height-statusBar.Size.Height);
			statusBar.Bounds = new Rectangle(0, ClientSize.Height-statusBar.Height, ClientSize.Width, statusBar.Height);
		}

		protected override void OnBackColorChanged(EventArgs e) {
			code.BackColor = BackColor;
			base.OnBackColorChanged(e);
		}

		public void SetValueText(string text) {
			this.valuePanel.Text = text;
		}

		public void SetArglistText(string text) {
			arglistTimer.Stop();
			arglistPanel.Text = text==null?"":text;
		}

		private void FileNew_Click(object sender, System.EventArgs e) {
			new Editor().Show();
		}

		private void FileSaveAs_Click(object sender, System.EventArgs e) {
			SaveAs();
		}

		private void FileOpen_Click(object sender, System.EventArgs e) {
			Stream myStream;
			OpenFileDialog openFileDialog1 = new OpenFileDialog();
			if (saveFileName!=null)
				openFileDialog1.InitialDirectory = Path.GetDirectoryName(saveFileName);

			//openFileDialog1.InitialDirectory = "c:\\" ;
			openFileDialog1.Filter = "Source files (*.meta;*.mscript)|*.meta;*.mscript|Scheme files (*.scm)|*.scm|Dump files (*.mdump)|*.mdump|All files (*.*)|*.*" ;
			openFileDialog1.FilterIndex = 1 ;
			openFileDialog1.RestoreDirectory = true ;

			if(openFileDialog1.ShowDialog() == DialogResult.OK) {
				if((myStream = openFileDialog1.OpenFile())!= null) {
					// Insert code to read the stream here.
					myStream.Close();
					if (Path.GetExtension(openFileDialog1.FileName)==".mdump") {
						LoadDumpFile(openFileDialog1.FileName);
					} else {
						Editor ed = FindEditor(FileToken.GetToken(openFileDialog1.FileName));
						if (ed.WindowState==FormWindowState.Minimized)
							ed.WindowState = FormWindowState.Normal;
						ed.BringToFront();
						//new Editor(openFileDialog1.FileName).Show();
					}
				}
			}
			openFileDialog1.Dispose();
		}

		public static void LoadDumpFile(string filename) {
			try {
				IFormatter formatter = new BinaryFormatter();
				Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
				Inspector.Inspect(formatter.Deserialize(stream));
				stream.Close();
			} catch (Exception ex) {
				MessageBox.Show(ex.Message, "Error reading dump file");
				Inspector.Inspect(ex);
			}
		}

		private void HandleModified(object sender, EventArgs e) {
			if (!(this is Listener) && !reallyModified)
				Text = Name+" *";
			reallyModified = true;
		}

		void ClearModified() {
			reallyModified = false;
			code.Modified = false;
			Text = Name;
		}

		private void HandleQuit(object sender, EventArgs e) {
			HandleClose(null, null);
		}

		private void HandleClose(object sender, CancelEventArgs e) {
			if (this==Listener.mainListener) {
				if (MessageBox.Show("Closing this window will exit Meta.  Do you wish to close?", "Exit", MessageBoxButtons.YesNo) == DialogResult.Yes) {
					if (CloseAllEditorWindows())
						e.Cancel|= true;
					else
						System.Environment.Exit(0);
				} else
					e.Cancel=true;
			} else {
				if (reallyModified) {
					switch (MessageBox.Show("Save file "+Name+"?", Name, MessageBoxButtons.YesNoCancel)) {
						case DialogResult.Yes:
							Save();
							break;

						case DialogResult.No:
							break;

						case DialogResult.Cancel:
							e.Cancel = true;
							break;
					}
				}
				if (!e.Cancel)
					RemoveFromEditorTable();
			}
		}

		void SaveAs() {
			SaveFileDialog saveFileDialog1 = new SaveFileDialog();
			if (saveFileName!=null)
				saveFileDialog1.InitialDirectory = Path.GetDirectoryName(saveFileName);
 
			//saveFileDialog1.Filter = "Code files (*.meta)|*.meta|All files (*.*)|*.*";
			saveFileDialog1.Filter = "Source files (*.meta)|*.meta|Autorun scripts (*.mscript)|*.mscript|All files (*.*)|*.*";
			saveFileDialog1.FilterIndex = 1 ;
			saveFileDialog1.RestoreDirectory = true ;
 
			if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
				try {
					code.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
					FileName = saveFileDialog1.FileName;
					Name = Path.GetFileName(FileName);
#if oldickysavefile
					Stream myStream ;
					if((myStream = saveFileDialog1.OpenFile()) != null) {
						FileName = saveFileDialog1.FileName;
						StreamWriter myStreamWriter = new StreamWriter(myStream);

						if (myStreamWriter != null) {				
							// Loop through the array and send the contents of the array to debug window.
							/*for(int counter=0; counter < code.Lines.Length; counter++)
							{
								myStreamWriter.Write(code.Lines[counter]);
								myStreamWriter.Write('\n');
							}*/
							myStreamWriter.Write(code.Rtf);

							myStreamWriter.Close();
						}

						myStream.Close();
				}
#endif
					ClearModified();
				} catch (Exception e) {
					e= e;
					MessageBox.Show("Couldn't save file "+saveFileName, "Problem saving file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					SaveAs();
				}
			}
			saveFileDialog1.Dispose();
		}

		static string tempDir = Path.Combine(Path.GetDirectoryName(System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory)),
			"Temp");
		bool IsTempFile(string path) {
			return false;
			//return path.StartsWith(tempDir);
		}

		public void Save() {
			code.NoteUserSelection();  // Needed for MarkUndo() in FinishReindentBeforeSave().
			code.FinishReindentBeforeSave();
			if (saveFileName == null)
				SaveAs();
			else if (IsTempFile(tempDir) && MessageBox.Show("This file appears to come from a temporary file directory that is not easily accessible.  This can occur if you open the file as a link in a browser or as an email attachment.  If you save the file here, it may be difficult to recover.  Would you like to save it to a different location?",
				"Saving temporary file", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)==DialogResult.Yes)
				SaveAs();
			else {
				try {
					// Some students have reported problems with files being truncated to zero length,
					// presumably because an error gets thrown saving the file but the OS has already
					// truncated it.  So we save in paranoid mode.
					string tempfile = this.FileName + ".new";
					code.SaveFile(tempfile, RichTextBoxStreamType.RichText);
					FileInfo i = new FileInfo(tempfile);
					if (i.Length>0) {
						if (System.IO.File.Exists(this.FileName))
							System.IO.File.Delete(this.FileName);
						i.MoveTo(this.FileName);
					}
#if oldickysavefile
					StreamWriter myStream = new StreamWriter(saveFileName,false);

					if (myStream != null) {				
						// Loop through the array and send the contents of the array to debug window.
						/*for(int counter=0; counter <= code.Lines.Length; counter++)
							{
								myStream.Write(code.Lines[counter]);
								myStream.Write('\n');
							}*/

						myStream.Write(code.Rtf);
						myStream.Close();
					}
#endif
					ClearModified();
				} catch (Exception e) {
					e= e;
					MessageBox.Show("Couldn't save file "+saveFileName, "Problem saving file", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					SaveAs();
				}
			}
		}

		private void FileSave_Click(object sender, System.EventArgs e) {
			Save();
		}

		private void FileClose_Click(object sender, System.EventArgs e) {
			Close();
		}

		public Expression ExpressionAt(int filelocation) {
			string definitionName = code.DefinitionNameAt(filelocation);
			Meta.Procedure fbinding = Namespace.CheckFbinding(definitionName);
			int start = code.StartOfDefinitionAt(filelocation);
			if (start>=0 && fbinding!=null)
				return ExpressionAtOffset(fbinding, filelocation-start);
			else
				return null;
		}

		LocalVariable FindLocalOfLambda(LambdaExpression l, string name) {
			foreach (LocalVariable v in l.argumentVariables) {
				if (v.name.name==name)
					return v;
			}
			return null;
		}

		Variable FindBinding(Expression e, string name) {
			while (e!=null) {
				if (e is LambdaExpression) {
					LocalVariable v = FindLocalOfLambda((LambdaExpression)e, name);
					if (v!=null)
						return v;
				} else if (e is Application) {
					Application a = (Application)e;
					if (a.function is LambdaExpression) {
						LocalVariable v = FindLocalOfLambda((LambdaExpression)a.function, name);
						if (v!=null)
							return v;
					}
				}
				e = e.enclosingExpression;
			}
			return Namespace.Lookup(Symbol.Intern(name), true, false, true);
		}

		public Expression ExpressionAtIncludingVariable(int filelocation) {
			CodeScanner sc = code.ScanCharsFrom(filelocation);
			if (Char.GetUnicodeCategory(sc.CurrentChar)==System.Globalization.UnicodeCategory.OpenPunctuation)
				// We're looking at a normal expression
				return ExpressionAt(filelocation);
			// We think we're looking at a variable reference.
			int start=sc.SkipBackwardToken();
			if (start>=0 && sc.CurrentChar!='[' && sc.CurrentChar!='(') {
				int end=sc.SkipForwardToken();
				if (end<code.TextLength) {
					string maybeVar=code.RegionText(new Region(start, end-start));
					int dot=maybeVar.IndexOf('.');
					if (dot>=0)
						maybeVar = maybeVar.Substring(0,dot);
					sc.MaybeSkipBackwardToEnclosingExpression();
					if (!sc.AtBeginningOfBuffer) {
						Expression enclosing = ExpressionAt(sc.charIndex);
						return FindBinding(enclosing, maybeVar);
					}
				}
			}
			return null;
		}

		internal Expression ExpressionAt(Procedure p, int filelocation) {
			int start = code.StartOfDefinitionAt(filelocation);
			if (start>=0)
				return ExpressionAtOffset(p, filelocation-start);
			else
				return null;
		}

		internal Expression ExpressionAtOffset(Procedure p, int offset) {
			if (Utilities.IsRemote(p))
				return null;
			InterpretedProcedureBase i = p as InterpretedProcedureBase;
			GenericProcedure g = p as GenericProcedure;
//			CodeScanner sc=code.ScanCharsFrom(filelocation);
//			if (Char.GetUnicodeCategory(sc.CurrentChar)!=System.Globalization.UnicodeCategory.OpenPunctuation) {
//				sc.SkipBackwardToEnclosingExpression();
//				filelocation = sc.charIndex;
//			}
			if (i!=null)
				return ExpressionAtOffset(i.sourceExpression, offset);
			else if (g!=null) {
				foreach (GenericProcedure.Method m in g.methodList) {
					InterpretedProcedureBase impl = m.implementation as InterpretedProcedureBase;
					if (impl!=null) {
						Expression e = ExpressionAtOffset(impl.sourceExpression, offset);
						if (e!=null)
							return e;
					}
				}
				return null;
			} else
				return null;
		}

		Expression ExpressionAtOffset(Expression e, int offset) {
			if (e==null)
				return null;

			if (e.SourceOffset==offset)
				return e;
			else
				foreach (Expression s in (IList)(e.Subexpressions)) {
					Expression result = ExpressionAtOffset(s, offset);
					if (result!=null)
						return result;
				}
			return null;
		}


#if ABSOLUTE_FILE_LOCATIONS
		internal Expression ExpressionAt(Procedure p, int filelocation) {
			if (Utilities.IsRemote(p))
				return null;
			InterpretedProcedureBase i = p as InterpretedProcedureBase;
			GenericProcedure g = p as GenericProcedure;
			CodeScanner sc=code.ScanCharsFrom(filelocation);
			if (Char.GetUnicodeCategory(sc.CurrentChar)!=System.Globalization.UnicodeCategory.OpenPunctuation) {
				sc.SkipBackwardToEnclosingExpression();
				filelocation = sc.charIndex;
			}
			if (i!=null)
				return ExpressionAt(i.sourceExpression, filelocation);
			else if (g!=null) {
				foreach (GenericProcedure.Method m in g.methodList) {
					InterpretedProcedureBase impl = m.implementation as InterpretedProcedureBase;
					if (impl!=null) {
						Expression e = ExpressionAt(impl.sourceExpression, filelocation);
						if (e!=null)
							return e;
					}
				}
				return null;
			} else
				return null;
		}
#endif

		Expression ExpressionAt(Expression e, int filelocation) {
			if (e==null)
				return null;

			if (e.sourceLocation==filelocation)
				return e;
			else
				foreach (Expression s in (IList)(e.Subexpressions)) {
					Expression result = ExpressionAt(s, filelocation);
					if (result!=null)
						return result;
				}
			return null;
		}

		private void MenuPop_Execute(object sender, System.EventArgs e) {
			bool running = (Listener.mainListener.evalThread != null && Listener.mainListener.evalThread.IsAlive);
			bool breakpointed = Meta.TopLevel.ThreadBeingDebugged!=null;

			code.NoteUserSelection();
			Evaluate.Enabled = !running || breakpointed;
			SingleStepMenuItem.Enabled = !running || breakpointed;
			Evaluate.Text = breakpointed?"Continue execution":"Execute";
			inspectMenuItem.Enabled = !running;
			executeSelectionMenuItem.Enabled = !running;
			executeAllMenuItem.Enabled = !running && !(this is Listener);
			loadMenuItem.Enabled = !running;

			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			breakpointMenuItem.Enabled = fbinding!= null;
			breakpointMenuItem.Checked = fbinding!=null && fbinding.Breakpointed;
			traceMenuItem.Enabled = fbinding!=null;
			traceMenuItem.Checked = fbinding!=null && fbinding.Traced;

			Expression exp = fbinding!=null?ExpressionAt(fbinding, code.userSelection.start):null;
			breakpointExpressionMenuItem.Enabled = exp!=null;
			breakpointExpressionMenuItem.Checked = exp!=null && exp.executionMode.Breakpoint;
			continueExecutionMenuItem.Enabled = breakpointExpressionMenuItem.Enabled && breakpointed;

			StopExec.Enabled = running;
			InterruptExecution.Enabled = running && !breakpointed;
			clearAllBreakpointsMenuItem.Enabled = Meta.TopLevel.BreakpointsSet;
			clearAllTracesMenuItem.Enabled = Meta.TopLevel.TracesSet;
			traceLoadMenuItem.Checked = Meta.TopLevel.TraceLoading;
			code.RestoreUserSelection();
			code.UnlockWindowDammit();
		}

		private void MenuPop_Advanced(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			lowLevelDebugMenuItem.Checked = Meta.TopLevel.lowLevelDebug;
			showDetailMenuItem.Checked = Inspector.showDetail;
			beginnerModeMenuItem.Checked = EvalStack.showAllExpressions
				&& Expression.OptimizeTailCalls.DefaultValue is bool && (bool)Expression.OptimizeTailCalls.DefaultValue==false
				&& Inspector.showDetail==false && Meta.TopLevel.AlwaysOpen2D;
			code.RestoreUserSelection();
			code.UnlockWindowDammit();
		}

		private void Breakpoint_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string varName = code.CurrentDefinitionVariable;
			object binding = this.Namespace.CheckBinding(varName);

			if (varName==null || varName=="")
				MessageBox.Show("The cursor isn't in a definition.", "Sorry, can't set breakpoint", MessageBoxButtons.OK);
			else if (binding==null)
				MessageBox.Show(varName + " isn't defined yet.", "Sorry, can't set breakpoint", MessageBoxButtons.OK);
			else if (binding is Meta.Procedure) {
				Meta.Procedure proc = (Meta.Procedure)binding;
				Meta.TopLevel.ToggleBreakpoint(proc);
				//proc.breakpoint = !proc.breakpoint;
				UpdateVariableValue();
			} else
				MessageBox.Show(varName + " isn't a function.", "Sorry, can't set breakpoint", MessageBoxButtons.OK);
				
			code.RestoreUserSelection();
		}

		private void Trace_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string varName = code.CurrentDefinitionVariable;
			object binding = this.Namespace.CheckBinding(varName);

			if (varName==null || varName=="")
				MessageBox.Show("The cursor isn't in a definition.", "Sorry, can't set tracing", MessageBoxButtons.OK);
			else if (binding==null)
				MessageBox.Show(varName + " isn't defined yet.", "Sorry, can't set tracing", MessageBoxButtons.OK);
			else if (binding is Meta.Procedure) {
				Meta.Procedure proc = (Meta.Procedure)binding;
				Meta.TopLevel.ToggleTrace(proc);
				//proc.breakpoint = !proc.breakpoint;
				UpdateVariableValue();
			} else
				MessageBox.Show(varName + " isn't a function.", "Sorry, can't set tracing", MessageBoxButtons.OK);
				
			code.RestoreUserSelection();
		}

		private void LowLevel_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.lowLevelDebug = !Meta.TopLevel.lowLevelDebug;
			lowLevelDebugMenuItem.Checked = Meta.TopLevel.lowLevelDebug;
		}

		private void SpeedUpEditor_Click(object sender, System.EventArgs e) {
			fastMode = !fastMode;
			speedUpEditorMenuItem.Checked = fastMode;
		}

		private void ShowDetail_Click(object sender, System.EventArgs e) {
			Inspector.showDetail = !Inspector.showDetail;
			showDetailMenuItem.Checked = Inspector.showDetail;
		}
		
		private void StopExec_Click(object sender, System.EventArgs e) {
			code.HandleStop(sender, e);
		}

		private void SelectAll_Click(object sender, System.EventArgs e) {
			code.HandleSelectAll(sender, e);
		}

		private void Cut_Click(object sender, System.EventArgs e) {
			code.HandleCut(sender, e);
		}

		private void Copy_Click(object sender, System.EventArgs e) {
			code.HandleCopy(sender, e);
		}

		private void Paste_Click(object sender, System.EventArgs e) {
			code.HandlePaste(sender, e);
		}

		private void Transpose_Click(object sender, EventArgs e) {
			code.HandleTranspose(sender, e);
		}

		private void Font_Click(object sender, System.EventArgs e) {
			code.HandleFont(sender, e);
		}

		private void Evaluate_Click(object sender, System.EventArgs e) {
			if (Meta.TopLevel.ThreadBeingDebugged!=null) {
				Meta.TopLevel.ThreadBeingDebugged.Continue();
				CodeBox.SuppressKeyUp(Keys.E);
			} else {
				Meta.TopLevel.CurrentSourceFileToken = fileToken;
				code.HandleEval(sender, e);
			}
		}

		private void SingleStep_Click(object sender, System.EventArgs e) {
			if (Meta.TopLevel.ThreadBeingDebugged != null) {
				Meta.TopLevel.ThreadBeingDebugged.Step();
			} else {
				Meta.TopLevel.CurrentSourceFileToken = fileToken;
				code.HandleStep(sender, e);
			}
			CodeBox.SuppressKeyUp(Keys.D1);
		}

		private void Inspect_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.CurrentSourceFileToken = fileToken;
			code.HandleInspect(sender, e);
		}

		private void EditMenu_Pop(object sender, EventArgs ea) {
			code.NoteUserSelection();
			Expression e = Expression.FindableExpression(code.CurrentVariableExpression);

			undoMenuItem.Enabled = code.undoEnabled;
			FindDefinitionMenuItem.Enabled = e!=null;
			FindDefinitionMenuItem.Text = (e==null)?"Find &Definition":("Find &Definition of "+e.definedIn);
			string var = code.CurrentDefinitionVariable;
			ShowReferencesMenuItem.Enabled = var!=null && var!="";
			ShowReferencesMenuItem.Text = ShowReferencesMenuItem.Enabled?("Show &references to "+var):"Show &references";
			var = code.CurrentVariableName;
			ShowReferencesMenuItem2.Enabled = var!=null && var!="";
			ShowReferencesMenuItem2.Text = ShowReferencesMenuItem2.Enabled?("Show &references to "+var):"Show &references";
			code.UnlockWindowDammit();
		}

		private void FindDefinition_Click(object sender, EventArgs ea) {
			EditSource(code.CurrentVariableExpression, false, true);
		}

		private void LangSpec_Click(object sender, System.EventArgs e) {
			new HelpBrowser("Manual.htm").Show();
		}

		private void FileExit_Click(object sender, System.EventArgs e) {
			Meta.Editor.Listener.mainListener.Close();
		}

		private void About_Click(object sender, System.EventArgs e) {
			AboutDialog aboutdlg = new AboutDialog();
			aboutdlg.ShowDialog();
		}

#if SYNTAXHIGHLIGHTING
		private void Pref_Click(object sender, System.EventArgs e)
		{
			Options options = new Options(code);
			options.Show();
		}
#endif

		private void PrinterSettingsMenu_Click(object sender, System.EventArgs e) {
			this.printDialog1.Document = this.ThePrintDocument;
			printDialog1.ShowDialog();
		}

		private void PreviewMenu_Click(object sender, System.EventArgs e) {
			try {
				// read string from editor window
				string strText = this.code.Text;
				myReader = new StringReader(strText);
				
				// instantiate new print preview dialog
				PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
				printPreviewDialog1.Document = this.ThePrintDocument;

				// Show the print preview dialog, uses print page event to draw preview screen
				printPreviewDialog1.ShowDialog();
			}
			catch(Exception exp) {
				MessageBox.Show("Printing Error: " + exp.Message + "\n" + exp.Source + "\n" + exp.TargetSite);
			}
		}

		private void FilePrint_Click(object sender, System.EventArgs e) {
			printDialog1.Document = ThePrintDocument;
			string strText = this.code.Text;
			myReader = new StringReader(strText);
			if (printDialog1.ShowDialog() == DialogResult.OK) {
				try {
					this.ThePrintDocument.Print();
				}
				catch (Exception ex) {
					MessageBox.Show("Error: " + ex.Message);
				}
			}
		}

		protected void ThePrintDocument_PrintPage (object sender, System.Drawing.Printing.PrintPageEventArgs ev) {
			float linesPerPage = 0;
			float yPosition = 0;
			int count = 0;
			float leftMargin = ev.MarginBounds.Left;
			float topMargin = ev.MarginBounds.Top; 
			string line = null;
			Font printFont = this.code.Font;
			SolidBrush myBrush = new SolidBrush(Color.Black);

			// Work out the number of lines per page, using the MarginBounds. 

			linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);

			// Iterate over the string using the StringReader, printing each line. 

			while(count < linesPerPage && ((line=myReader.ReadLine()) != null)) {

				// calculate the next line position based on
				// the height of the font according to the printing device 

				yPosition = topMargin + (count * printFont.GetHeight(ev.Graphics));

				// draw the next line in the rich edit control 

				ev.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());

				count++;
			}

			// If there are more lines, print another page. 

			if  (line != null)
				ev.HasMorePages = true;
			else
				ev.HasMorePages = false;

			myBrush.Dispose();
		}

#if SYNTAXHIGLIGHTING
		// Handle a user clicking on the "Syntax Highlighting" Menu.
		private void HighLightMenu_Click(object sender, System.EventArgs e) {
			if (EditorConfiguration.canHighlight) {
				HighLightMenu.Checked = EditorConfiguration.doComment = !HighLightMenu.Checked;
				if (HighLightMenu.Checked)
					code.SyntaxHighlight();
				else
					code.SyntaxUnhighlight();
			}
		}
#endif

		private void EvalFile_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.CurrentSourceFileToken = FileToken.GetToken(saveFileName);
			code.HandleEvalFile(sender, e);
		}

		private void EvalRegion_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.CurrentSourceFileToken = FileToken.GetToken(saveFileName);
			code.HandleEvalRegion(sender, e);
		}

		private void CntxtSelAll_Click(object sender, System.EventArgs e) {
			code.HandleSelectAll(sender, e);
		}

		private void CntxtCut_Click(object sender, System.EventArgs e) {
			code.HandleCut(sender, e);
		}

		private void CntxtCopy_Click(object sender, System.EventArgs e) {
			code.HandleCopy(sender, e);
		}

		private void CntxtPste_Click(object sender, System.EventArgs e) {
			code.HandlePaste(sender, e);
		}

		private void Undo_Click(object sender, System.EventArgs e) {
			code.HandleUndo(sender, e);
		}

		void FormatMenuPop(object sender, EventArgs e) {
			code.FormatMenuPop(formatBold, formatItalic, formatBullet);
		}

		void FormatBoldClick(object sender, EventArgs e) {
			code.FormatBoldClick(sender,e);
		}
		void FormatItalicClick(object sender, EventArgs e) {
			code.FormatItalicClick(sender,e);
		}
		void FormatGrowClick(object sender, EventArgs e) {
			code.FormatGrowClick(sender,e);
		}
		void FormatShrinkClick(object sender, EventArgs e) {
			code.FormatShrinkClick(sender,e);
		}
		void FormatSuperscriptClick(object sender, EventArgs e) {
			code.FormatSuperscriptClick(sender,e);
		}
		void FormatSubscriptClick(object sender, EventArgs e) {
			code.FormatSubscriptClick(sender,e);
		}
		void FormatBulletClick(object sender, EventArgs e) {
			code.FormatBulletClick(sender, e);
		}


		void MaybeShowArglist(object sender, EventArgs e) {
			if (code.WindowLocked)
				return;
			arglistTimer.Stop();
			if (!fastMode && !code.iSearchMode)
				MaybeShowArglist();
		}

		void MaybeShowArglist() {
			arglistOperator = code.CurrentExpressionOperator;
			SetArglistText(GetArglist(arglistOperator));
			arglistTimer.Start();
		}

		void ShowDocumentation(object sender, EventArgs e) {
			if (arglistOperator != null) {
				string docs = Utilities.Documentation(this.Namespace.CheckBinding(arglistOperator));
				if (docs!=null)
					SetArglistText(docs);
			}
		}

		string GetArglist(string variableName) {
			if (variableName==null)
				return null;
			int point = variableName.LastIndexOf('.');
			if (point>0) {
				MemberInfo[] methods = ResolveCSName(variableName) as MemberInfo[];
				if (methods==null || methods.Length==0)
					return null;
					//					else if (methods.Length>1)
					//						return "Arguments vary";
				else if (!(methods[0] is MethodInfo))
					return null;
				else
					return FormatMethodArgInfo(variableName, (MethodInfo)methods[0])+((methods.Length>1)?(" + "+methods.Length.ToString()+" overloads"):"");
			} else {
				object op = this.Namespace.CheckBinding(variableName);
				object[] arglist=Utilities.Arglist(op);
	
				if (arglist != null) {
					string[] prototype = new string[2*arglist.Length+ 3];

					prototype[0] = "[";
					prototype[1] = variableName;
					prototype[2] = " ";
					for (int i=0; i< arglist.Length; i++) {
						prototype[2*i+3] = (arglist[i] is string)?(string)arglist[i]:((Meta.Symbol)arglist[i]).name;
						prototype[2*i+4] = " ";
					}
					prototype[prototype.Length-1] = "]";
					return string.Concat(prototype);
				} else
					return null;
			}
		}

		object ResolveCSName(string csName) {
			int point = csName.LastIndexOf('.');
			if (point<0)
				return this.Namespace.CheckBinding(csName);
			else if (point==0 || point==csName.Length-1)
				return null;  // Malformed expression
			else {
				string expr = csName.Substring(0, point);
				string memberName = csName.Substring(point+1, csName.Length-(point+1));
				object ob = ResolveCSName(expr);
				Type asType = ob as Type;

				try {
					if (ob==null)
						return null;
					else if (asType==null)
						// It's a regular object
						return ob.GetType().GetMember(memberName);
					else
						// It's a type name
						return asType.GetMember(memberName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
				} catch {
					return null;
				}
			}
		}

		string FormatMethodArgInfo(string expr, MethodInfo m) {
			ParameterInfo[] p = m.GetParameters();
			String[] strings = new String[2*p.Length+3];

			strings[0] = "[";
			strings[1] = expr;
			strings[2] = " ";
			for (int i=0; i<p.Length; i++) {
				strings[2*i+3] = p[i].Name;
				strings[2*i+4] = " ";
			}
			strings[strings.Length-1] = "]";
			return string.Concat(strings);
		}
		
		void UpdateVariableValue() {
			string variableName = code.CurrentDefinitionVariable;

			if (variableName != null) {
				object binding=code.LookupMemberExpression(variableName);
				if (binding != null)
					SetValueText(Meta.Writer.SafeWriteToString(binding, 100));
			}
		}

		void AproposClick(object sender, EventArgs e) {
			AproposForm f = AproposForm.theAproposForm;
			code.MaybeUnlockWindow();

			f.ShowDialog();
			if (f.DialogResult == DialogResult.OK)
				Meta.Apropos.ShowApropos(f.keyword.Text);
		}

		private void InterruptExecution_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.SingleStepMode = true;
		}

		static OpenFileDialog examplesDialog = new OpenFileDialog();
		private void examplesMenuItem_Click(object sender, System.EventArgs e) {
			examplesDialog.Filter = "Meta source code (*.meta)|*.meta";
			examplesDialog.InitialDirectory = Meta.Installation.installDirectory+new string(Path.DirectorySeparatorChar, 1)+"Examples";
			if (examplesDialog.ShowDialog()==DialogResult.OK)
				new Editor(examplesDialog.FileName).Show();
		}

		private void backgroundColorMenuItem_Click(object sender, System.EventArgs e) {
			colorDialog.AnyColor = true;
			colorDialog.Color = code.BackColor;
			if (colorDialog.ShowDialog()==DialogResult.OK)
				code.BackColor = colorDialog.Color;
		}

		private void forceGCMenuItem_Click(object sender, System.EventArgs e) {
			if (!Listener.IsRunning)
				EvalStack.CurrentThreadEvalStack.ClearForGC();
			System.GC.Collect();
			System.GC.WaitForPendingFinalizers();
		}

		private void loadMenuItem_Click(object sender, System.EventArgs e) {
			code.HandleLoadFile(sender, e);
		}

		private void pasteCommandMenuItem_Click(object sender, System.EventArgs e) {
			code.PastePreviousCommand();
		}

		private void menuItem8_Click(object sender, System.EventArgs e) {
			code.PasteNextCommand();
		}

		private void ApplyStyle(object sender, System.EventArgs e) {
			code.HandleStyle(sender, e);
		}

		private void EditStyles_Click(object sender, System.EventArgs e) {
			new StyleEditor(code).ShowDialog();
		}

		private void setDefaultMenuItem_Click(object sender, System.EventArgs e) {
			code.RecordDefaults();
		}

		private void contextMenu1_Popup(object sender, System.EventArgs ea) {
			code.NoteUserSelection();
			bool running = (Listener.mainListener.evalThread != null && Listener.mainListener.evalThread.IsAlive);
			bool breakpointed = Meta.TopLevel.ThreadBeingDebugged!=null;

			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			contextExecute.Enabled = !running || breakpointed;
			contextSingleStep.Enabled = !running || breakpointed;
			contextBreakpoint.Enabled = fbinding!= null;
			contextBreakpoint.Checked = fbinding!=null && fbinding.Breakpointed;
			contextTrace.Enabled = fbinding!=null;
			contextTrace.Checked = fbinding!=null && fbinding.Traced;

			Expression exp = fbinding!=null?ExpressionAt(fbinding, code.userSelection.start):null;
			contextBreakpointExpressionMenuItem.Enabled = exp!=null;
			contextBreakpointExpressionMenuItem.Checked = exp!=null && exp.executionMode.Breakpoint;
			traceAnalysisMenuItem.Enabled = exp!=null;
			traceAnalysisMenuItem.Checked = exp!=null && exp.traceAnalysis;
			contextContinueExecutionMenuItem.Enabled = contextBreakpointExpressionMenuItem.Enabled && breakpointed;
			

			Expression e = Expression.FindableExpression(code.CurrentVariableExpression);
			contextFindDefinition.Enabled = e!=null;
			contextFindDefinition.Text = (e==null)?"Find &Definition":("Find &Definition of "+e.definedIn);
			contextFindUsesMenuItem.Enabled = e!=null;
			contextFindUsesMenuItem.Text = (e==null)?"Find &uses":("Find &uses of "+e.definedIn);

			code.RestoreUserSelection();
			code.UnlockWindowDammit();
		}

		private void findMenuItem_Click(object sender, System.EventArgs e) {
			FindDialog f = new FindDialog(code);
			f.Show();
		}

		private void tailRecursionMenu_Popup(object sender, System.EventArgs e) {
			object opt = Expression.OptimizeTailCalls.DefaultValue;

			fullTailRecursionMenuItem.Checked = opt==Symbol.sAll;
			selfTailRecursionMenuItem.Checked = opt==Symbol.sSelf;
			noTailRecursionMenuItem.Checked = !selfTailRecursionMenuItem.Checked && !fullTailRecursionMenuItem.Checked;
		}

		private void fullTailRecursionMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = Symbol.sAll;
		}

		private void selfTailRecursionMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = Symbol.sSelf;
		}

		private void noTailRecursionMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = false;
		}

		private void ReindentMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatExpression(code, code.TopLevelExpressionRegion(code.userSelection.start).Start, false, false, true);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		protected void ReindentAllMenuItem_Click(object sender, System.EventArgs e) {
			ReindentAll();
		}

		public void ReindentAll() {
			code.LockWindow();
			code.NoteUserSelection();
			Formatter.FormatBuffer(code, false, false);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void restyleMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatExpression(code, code.TopLevelExpressionRegion(code.userSelection.start).Start, true, true, true);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void restyleAllMenuItem_Click(object sender, System.EventArgs e) {
			RestyleAll();
		}

		public void RestyleAll() {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatBuffer(code, true, true);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void restyleAllPreservingCommentsMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.MarkUndo();
			code.LockWindow();
			Formatter.FormatBuffer(code, true, false);
			code.RestoreUserSelection();
			code.UnlockWindow();
		}

		private void clearAllBreakpointsMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.ClearAllBreakpoints();
		}

		private void clearAllTracesMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.ClearAllTraces();
		}

		private void breakpointExpressionMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			Expression exp = ExpressionAt(fbinding, code.userSelection.start);
			if (exp!=null)
				Meta.TopLevel.ToggleBreakpoint(exp);
			code.RestoreUserSelection();
		}

		private void continueExecutionMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			string definitionName = code.CurrentDefinitionVariable;
			Meta.Procedure fbinding = this.Namespace.CheckFbinding(definitionName);

			Expression exp = ExpressionAt(fbinding, code.userSelection.start);
			if (exp!=null)
				Meta.TopLevel.ThreadBeingDebugged.ContinueUntil(exp);
			code.RestoreUserSelection();
			CodeBox.SuppressKeyUp(Keys.C);
		}

		private void beginnerModeMenuItem_Click(object sender, System.EventArgs e) {
			Expression.OptimizeTailCalls.DefaultValue = false;
			Inspector.showDetail = false;
			EvalStack.showAllExpressions=true;
			Meta.TopLevel.AlwaysOpen2D = true;
		}

		private void windowsMenu_Select(object sender, System.EventArgs e) {
			ArrayList items = new ArrayList();

			for (int j=windowsMenu.MenuItems.Count-1; j>=2; j--)
				windowsMenu.MenuItems.RemoveAt(j);
			foreach (DictionaryEntry d in editorTable) {
				if (d.Value!=null) {
					Editor ed = (Editor)(d.Value);
					items.Add(new MenuItem(ed.Text, new EventHandler(ed.WindowSelectHandler)));
				}
			}
			items.Sort(MenuComparer.Comparer);
			foreach (MenuItem i in items)
				windowsMenu.MenuItems.Add(i);
			windowsMenu.MenuItems[2].Text = "&"+windowsMenu.MenuItems[2].Text;
			for (int j = 3; j<windowsMenu.MenuItems.Count && j<=13; j++)
				windowsMenu.MenuItems[j].Text = "&"+(j-2).ToString()+"  "+windowsMenu.MenuItems[j].Text;
		}
		private void WindowSelectHandler(object sender, EventArgs e) {
			BringToFront();
			if (WindowState==FormWindowState.Minimized)
				WindowState=FormWindowState.Normal;
		}

		private void traceLoadMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.TraceLoading = !Meta.TopLevel.TraceLoading;
		}

		public float ZoomFactor {
			get {
				return code.ZoomFactor;
			}
			set {
				code.ZoomFactor = value;
			}
		}

		private void zoomMenu_Popup(object sender, System.EventArgs e) {
			zoom300.Checked = zoom200.Checked = zoom150.Checked = zoom120.Checked = zoom110.Checked
				= zoom100.Checked = zoom90.Checked = zoom80.Checked = false;
			
			if (ZoomFactor==3.0F)
				zoom300.Checked = true;
			else if (ZoomFactor==2.0F)
				zoom200.Checked = true;
			else if (ZoomFactor==1.5F)
				zoom150.Checked = true;
			else if (ZoomFactor==1.2F)
				zoom120.Checked = true;
			else if (ZoomFactor==1.1F)
				zoom110.Checked = true;
			else if (ZoomFactor==1.0F)
				zoom100.Checked = true;
			else if (ZoomFactor==0.9F)
				zoom90.Checked = true;
			else if (ZoomFactor==0.8F)
				zoom80.Checked = true;
		}

		private void zoom100_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.0F;
		}

		private void zoom90_Click(object sender, System.EventArgs e) {
			ZoomFactor = 0.9F;
		}

		private void zoom80_Click(object sender, System.EventArgs e) {
			ZoomFactor = 0.8F;
		}

		private void zoom110_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.1F;
		}

		private void zoom120_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.2F;
		}

		private void zoom150_Click(object sender, System.EventArgs e) {
			ZoomFactor = 1.5F;
		}

		private void zoom200_Click(object sender, System.EventArgs e) {
			ZoomFactor = 2.0F;
		}

		private void zoom300_Click(object sender, System.EventArgs e) {
			ZoomFactor = 3.0F;
		}

		private void ShowReferences_Click(object sender, System.EventArgs e) {
			code.HandleShowReferences(true);
		}

		private void ShowReferences2_Click(object sender, System.EventArgs e) {
			code.HandleShowReferences(false);
		}

		private void ISearchMenuItem_Click(object sender, System.EventArgs e) {
			if (code.iSearchMode)
				code.ISearchNext();
			else
				code.StartISearch();
		}

		private void FKeyMenuItem_Popup(object sender, System.EventArgs e) {
			bool gotOne = false;
			object titleob = Namespace.CheckBinding("menu-title");
			string title = (titleob!=null)?(titleob as string):null;
			foreach (FKeyMenuItem i in fKeyMenuItem.MenuItems) {
				i.Update();
				gotOne |= i.Enabled;
			}
			fKeyMenuItem.Visible = fKeyMenuItem.Enabled = gotOne;
			if (title!=null)
				fKeyMenuItem.Text = title;
		}

		private void ReplaceMenuItem_Click(object sender, System.EventArgs e) {
			ReplaceDialog f = new ReplaceDialog(code);
			f.Show();
			//f.Dispose();
		}

		private void RemoveWhitespaceMenuItem_Click(object sender, System.EventArgs e) {
			RemoveWhitespace();
		}

		public void RemoveWhitespace() {
			code.LockWindow();
			code.RemoveLeadingWhitespace();
			SetArglistText("Reindenting and restyling ...");
			Formatter.FormatBuffer(code, true, false);
			code.UnlockWindow();
			SetArglistText("Done");
			ShowNamespace();
		}

		private void CheckMenuItem_Click(object sender, System.EventArgs e) {
			Listener.mainListener.EvalString("[Packages.Analysis.check-namespace]", false, false, fileToken, 0, false);
		}

		static void UpdateAllCheckMenus(Namespace n) {
			foreach (DictionaryEntry d in editorTable) {
				Editor e = d.Value as Editor;
				if (e!=null && e.Namespace==n)
					e.UpdateCheckMenuStatus();
			}
		}

		void UpdateCheckMenuStatus() {
			if (Namespace.HasWarnings) {
				int warnings=0;
				foreach (DictionaryEntry e in Namespace.Warnings) {
					ArrayList expressions = (ArrayList)e.Value;
					warnings += expressions.Count;
				}
				CheckMenu.Text = string.Format("&Check ({0})", warnings);
			} else
				CheckMenu.Text = "&Check";
		}

		private void CheckMenu_Popup(object sender, System.EventArgs ignore) {
			int warning;
			// Find first WarningMenu
			for (warning=0; warning<CheckMenu.MenuItems.Count && !(CheckMenu.MenuItems[warning] is WarningMenu); warning++);
			// Remove everything after it
			for (int i=CheckMenu.MenuItems.Count-1; i>=warning; i--)
				CheckMenu.MenuItems.RemoveAt(i);
			// Repopulate it.
			if (Namespace.Warnings!=null) {
				try {
					ArrayList headings = new ArrayList();
					foreach (DictionaryEntry e in this.Namespace.Warnings)
						headings.Add(e.Key);
					headings.Sort();
					foreach (string heading in headings) {
						IList exps = (IList)(Namespace.Warnings[heading]);
						if (exps.Count>0)
							CheckMenu.MenuItems.Add(new WarningMenu(heading, exps));
					}
				} catch {}
			}
			AutoCheckMenuItem.Checked = Meta.TopLevel.AutoCheck;
		}

		private void AutoCheckMenuItem_Click(object sender, System.EventArgs e) {
			Meta.TopLevel.AutoCheck = !Meta.TopLevel.AutoCheck;
		}

		private void GotoMenuItem_Pop(object sender, System.EventArgs e) {
			ArrayList items = new ArrayList();
			code.LockWindow();
			CodeBox.ScrollPoint scroll = code.ScrollPosition;
			GotoMenuItem.MenuItems.Clear();
			code.NoteUserSelection();
			CodeScanner s = code.ScanCharsFrom(0);
			while (!s.AtEndOfBuffer) {
				if ((s.LookingAt("[define") || s.LookingAt("(define"))
					&& code.RegionIndent(new Region(s.charIndex,0))==0) {
					string line = code.Lines[s.lineNumber];
					string title = line;
					int space = line.IndexOf(' ');
					if (space>=0)
						title = line.Substring(space+1, line.Length-(space+1));
					items.Add(new MenuItem(title, new EventHandler(new GotoHandler(code, s.charIndex).Click)));
				}
				s.SkipForwardToBOL();
			}
			items.Sort(MenuComparer.Comparer);
			foreach (MenuItem i in items)
				GotoMenuItem.MenuItems.Add(i);
			code.RestoreUserSelection();
			code.ScrollPosition = scroll;
			code.UnlockWindowDammit();
		}

		private void RecenterMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			code.ScrollToCenter();
		}

		private void contextFindUsesMenuItem_Click(object sender, System.EventArgs e) {
			code.HandleShowReferences(false);
		}

		private void traceAnalysisMenuItem_Click(object sender, System.EventArgs e) {
			code.NoteUserSelection();
			Expression exp = ExpressionAtIncludingVariable(code.userSelection.start);
			if (exp!=null) {
				if (exp is GlobalVariableReference)
					exp = ((GlobalVariableReference)exp).variable;
				exp.traceAnalysis = !exp.traceAnalysis;
			}
		}

		private class GotoHandler {
			int index;
			CodeBox code;
			public GotoHandler(CodeBox code, int index) {
				this.code = code;
				this.index = index;
			}

			public void Click(object sender, EventArgs e) {
				code.userSelection = new Region(index, 0);
				code.RestoreUserSelection();
				code.ScrollToTop();
			}
		}

		private class MenuComparer : IComparer {
			public static MenuComparer Comparer = new MenuComparer();

			#region IComparer Members

			public int Compare(object x, object y) {
				string xt = ((MenuItem)x).Text;
				string yt = ((MenuItem)y).Text;

				if (xt==Listener.ListenerTitle && yt==Listener.ListenerTitle)
					return 0;
				else if (xt==Listener.ListenerTitle)
					return -1;
				else if (yt==Listener.ListenerTitle)
					return 1;
				else
					return String.Compare(xt, yt);
			}

			#endregion

		}

		public class CodeFileMenuItem : MenuItem {
			public CodeFileMenuItem(string name, string fileName) {
				this.Text = name;
				this.fileName = fileName;
				Click += new EventHandler(ShowFile);
			}
			public CodeFileMenuItem(string name, string fileName, Shortcut shortcut) {
				this.Text = name;
				this.fileName = fileName;
				Click += new EventHandler(ShowFile);
				this.Shortcut = shortcut;
			}
			string fileName;

			public void ShowFile(object sender, EventArgs e) {
				new Editor(fileName).Show();
			}
		}

		public class FKeyMenuItem : MenuItem {
			public FKeyMenuItem(Shortcut key) {
				this.Shortcut = key;
			}
			protected override void OnClick(EventArgs e) {
				Listener.mainListener.EvalString("["+Shortcut.ToString()+"]", false, false, ((Editor)GetMainMenu().GetForm()).fileToken, 0, true);
			}

			public void Update() {
				Editor e = (Editor)GetMainMenu().GetForm();
				Meta.Procedure p = e.Namespace.CheckFbinding(Shortcut.ToString());
				if (p!= null) {
					Visible = Enabled = true;
					Text = (((IDocumentable)p).Documentation==null)?"Run procedure named":((IDocumentable)p).Documentation;
				} else {
					Visible = Enabled = false;
				}
			}
		}
	}
}
